How to get only values in arrays with MongoDB aggregate?

To get only values from arrays in MongoDB aggregate operations, use the $map operator within $project to transform array elements and extract specific field values into a new array structure.

Syntax

db.collection.aggregate([
    {
        $project: {
            arrayField: {
                $map: {
                    input: "$arrayField",
                    as: "item",
                    in: ["$$item.field1", "$$item.field2"]
                }
            }
        }
    }
]);

Sample Data

db.demo411.insertOne({
    "Information": [
        {
            "Name1": "Chris",
            "Name2": "David"
        },
        {
            "Name1": "John",
            "Name2": "John"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e70f19715dc524f70227682")
}

Display Current Document

db.demo411.find();
{
    "_id": ObjectId("5e70f19715dc524f70227682"),
    "Information": [
        { "Name1": "Chris", "Name2": "David" },
        { "Name1": "John", "Name2": "John" }
    ]
}

Example: Extract Array Values

Extract only the Name1 and Name2 values from the Information array ?

db.demo411.aggregate([
    {
        $project: {
            _id: 0,
            Information: {
                $map: {
                    input: "$Information",
                    as: "out",
                    in: ["$$out.Name1", "$$out.Name2"]
                }
            }
        }
    }
]);
{ "Information": [ [ "Chris", "David" ], [ "John", "John" ] ] }

How It Works

  • $map iterates through each element in the Information array
  • input specifies the source array field
  • as creates a variable name for each array element
  • in defines the transformation - creates a new array with extracted values

Conclusion

Use $map with $project to extract specific field values from array elements. This transforms complex nested objects into simplified arrays containing only the values you need.

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

970 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements