Search code examples
mongodbdictionarymongoosemongodb-queryaggregation

How to turn a MongoDB query into a dictionary


I have a collection in my MongoDB:

{ userId: 1234, name: 'Mike' }
{ userId: 1235, name: 'John' }
...

I want to get a result of the form

dict[userId] = document

in other words, I want a result that is a dictionary where the userId is the key and the rest of the document is the value.

How can I do that?


Solution

  • You can use $arrayToObject to do that, you just need to format it to array of k, v before.

    It is not clear if you want one dictionary for all documents, or each document in a dictionary format. I guess you want the first option, but I'm showing both:

    One dictionary with all data*, requires a $group (which also format the data):

    db.collection.aggregate([
       {
        $group: {
          _id: null,
          data: {$push: {k: {$toString: "$userId"},  v: "$$ROOT"}}
        }
      },
      {
        $project: {data: {$arrayToObject: "$data"}}
      },
      {
        $replaceRoot: {newRoot: "$data"}
      }
    ])
    

    See how it works on the playground example - one dict

    *Notice that in this option, all the data is inserted to one document, and document as a limit size.

    Dictionary format: If you want to get all documents as different results, but with a dictionary format, just replace the first step of the aggregation with this:

     {
        $project: {
          data: [{k: {$toString: "$userId"}, v: "$$ROOT"}],
          _id: 0
        }
      },
    

    See how it works on the playground example - dict per document