MongoDB query to convert an array to a map of documents with n attributes?


For this, you can use $map. Let us first create a collection with documents −

> db.demo398.insertOne({
...    "details":[
...       {
...          "Name":"Chris",
...          "Age":22
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5e8cedfac4d418a017856c")
}

Display all documents from a collection with the help of find() method −

> db.demo398.find();

This will produce the following output −

{ "_id" : ObjectId("5e5e8cedfac4d418a017856c"), "details" : [ { "Name" : "Chris", "Age" : 22 } ] }

Following is the query to convert an array to a map of documents with n attributes −

> db.demo398.aggregate([
...    {
...       "$addFields": {
...          "details": {
...             "$arrayToObject": {
...                "$map": {
...                   "input": "$details",
...                   "as": "out",
...                   "in": {
...                      "k": "$$out.Name",
...                      "v": "$$out"
...                   }
...                }
...             }
...          }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : ObjectId("5e5e8cedfac4d418a017856c"), "details" : { "Chris" : { "Name" : "Chris", "Age" : 22 } } }

Updated on: 03-Apr-2020

650 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements