MongoDB query to limit subdocuments having the given fields of the 'projection'

To limit subdocuments having specific fields during projection in MongoDB, use the aggregation pipeline with $match, $unwind, and $project stages to filter and reshape the data.

Syntax

db.collection.aggregate([
    { $match: { "arrayField.targetField": { $exists: 1 } } },
    { $unwind: "$arrayField" },
    { $match: { "arrayField.targetField": { $exists: 1 } } },
    { $project: { "newField": "$arrayField.targetField", "_id": 0 } }
]);

Sample Data

db.demo285.insertOne({
    details: [
        {
            Name: "Chris"
        },
        {
            Name2: "Bob"
        },
        {
            Name: "Mike"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e4abffef49383b52759cbb9")
}

Display All Documents

db.demo285.find();
{
    "_id": ObjectId("5e4abffef49383b52759cbb9"),
    "details": [
        { "Name": "Chris" },
        { "Name2": "Bob" },
        { "Name": "Mike" }
    ]
}

Example: Limit Subdocuments with "Name" Field

Filter subdocuments that contain the "Name" field and project only those values ?

db.demo285.aggregate([
    { $match: { "details.Name": { $exists: 1 } } },
    { $unwind: "$details" },
    { $match: { "details.Name": { $exists: 1 } } },
    { $project: { Name: "$details.Name", _id: 0 } }
]);
{ "Name": "Chris" }
{ "Name": "Mike" }

How It Works

  • First $match: Filters documents containing the target field in the array
  • $unwind: Deconstructs the array into separate documents
  • Second $match: Filters individual subdocuments with the target field
  • $project: Shapes the output to show only desired fields

Conclusion

Use aggregation pipeline with $match, $unwind, and $project to filter subdocuments by specific fields. This approach effectively limits results to subdocuments containing the target field while reshaping the output structure.

Updated on: 2026-03-15T02:17:57+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements