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

To convert an array to a map of documents with n attributes in MongoDB, use the $arrayToObject operator combined with $map. This transforms array elements into key-value pairs where each document becomes a property of the resulting object.

Syntax

db.collection.aggregate([
    {
        "$addFields": {
            "fieldName": {
                "$arrayToObject": {
                    "$map": {
                        "input": "$arrayField",
                        "as": "item",
                        "in": {
                            "k": "$$item.keyField",
                            "v": "$$item"
                        }
                    }
                }
            }
        }
    }
])

Sample Data

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

Example

Display the original document structure ?

db.demo398.find();
{ "_id": ObjectId("5e5e8cedfac4d418a017856c"), "details": [ { "Name": "Chris", "Age": 22 } ] }

Convert the array to a map using the Name field as the key ?

db.demo398.aggregate([
    {
        "$addFields": {
            "details": {
                "$arrayToObject": {
                    "$map": {
                        "input": "$details",
                        "as": "out",
                        "in": {
                            "k": "$$out.Name",
                            "v": "$$out"
                        }
                    }
                }
            }
        }
    }
])
{ "_id": ObjectId("5e5e8cedfac4d418a017856c"), "details": { "Chris": { "Name": "Chris", "Age": 22 } } }

How It Works

  • $map iterates through each array element
  • k defines the key (using Name field value)
  • v defines the value (the entire document)
  • $arrayToObject converts the key-value pairs into an object

Conclusion

The $arrayToObject and $map combination effectively transforms arrays into objects, making it easier to access documents by their attribute values as keys rather than array indices.

Updated on: 2026-03-15T02:50:22+05:30

814 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements