I’m building a MongoDB/Mongoose query using the aggregate pipeline in a NodeJS/Express app. I’m trying to take an array of documents and convert it into a single object with the keys as the “_id” fields of each doc, and the values as the entire unedited document itself. I’ve dug into $group, $unwind, $arrayToObject, etc. and I think I can use a combination of things to get the result I’m looking for, maybe. This is basically what I’m trying to accomplish:
Take this:
[
{ _id: 41, myData: 'blah' },
{ _id: 42, myData: 'blah' },
{ _id: 43, myData: 'blah' }
]
and convert it to this:
{
41: { _id: 41, myData: 'blah' },
42: { _id: 42, myData: 'blah' },
43: { _id: 43, myData: 'blah' }
}
Specifically, I don’t know how to reference the entire document to add it as a value in a new field. For instance, I was thinking about using $group
to take each input document and output a new document like this: { _id: 42, myData: 'blah' }
–> { k: 42, v: { _id: 42, myData: 'blah' } }
and then I could use $arrayToObject
to create the single object I’m looking for. Maybe there’s a better, more performant option.