How do you convert an array of ObjectIds into an array of embedded documents with a field containing the original array element value?

To convert an array of ObjectIds into an array of embedded documents with a field containing the original array element value, use the $map operator within an aggregation pipeline. This transformation embeds each original array element as a value within a new document structure.

Syntax

db.collection.aggregate([
    {
        $addFields: {
            arrayField: {
                $map: {
                    input: "$arrayField",
                    in: { fieldName: "$$this" }
                }
            }
        }
    }
])

Sample Data

db.demo343.insertOne({
    _id: 101,
    UserName: "Chris",
    details: [
        {"Name": "John"},
        {"Name": "David"}
    ]
});
{ "acknowledged": true, "insertedId": 101 }

Original Document Structure

db.demo343.find().pretty();
{
    "_id": 101,
    "UserName": "Chris",
    "details": [
        {
            "Name": "John"
        },
        {
            "Name": "David"
        }
    ]
}

Example: Converting Array Elements

db.demo343.aggregate([
    {
        $addFields: {
            details: {
                $map: {
                    input: "$details",
                    in: { Name: "$$this" }
                }
            }
        }
    },
    { $out: "demo343" }
]);

Result After Conversion

db.demo343.find().pretty();
{
    "_id": 101,
    "UserName": "Chris",
    "details": [
        {
            "Name": {
                "Name": "John"
            }
        },
        {
            "Name": {
                "Name": "David"
            }
        }
    ]
}

How It Works

  • $map transforms each element in the input array
  • $$this represents the current array element being processed
  • Each original element becomes the value of the specified field in the new document structure
  • $out saves the transformed documents back to the collection

Conclusion

Use $map with $$this to convert array elements into embedded documents. This technique preserves the original data while restructuring it into a nested format with each element as a field value.

Updated on: 2026-03-15T02:33:49+05:30

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements