How to filter some fields in objects and fetch a specific subject name value in MongoDB?

To filter and fetch specific fields from objects in MongoDB, use the aggregation pipeline combining $match, $project, and $filter operators to target specific array elements and extract only the desired fields.

Syntax

db.collection.aggregate([
    { $match: { "arrayField.field": "value" } },
    { $project: {
        arrayField: {
            $filter: {
                input: "$arrayField",
                as: "item",
                cond: { $eq: ["$$item.field", "value"] }
            }
        }
    }},
    { $project: { "arrayField.specificField": 1 } }
]);

Sample Data

db.demo507.insertOne({
    "Information": [
        {"Name": "John", "SubjectName": "MySQL"},
        {"Name": "Bob", "SubjectName": "MongoDB"},
        {"Name": "Chris", "SubjectName": "MySQL"},
        {"Name": "David", "SubjectName": "C++"}
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e8836d3987b6e0e9d18f577")
}

Example: Filter MySQL Subjects and Show Only SubjectName

To filter objects with SubjectName "MySQL" and return only the SubjectName field ?

db.demo507.aggregate([
    { $match: { "Information.SubjectName": "MySQL" } },
    { $project: {
        _id: 0,
        Information: {
            $filter: {
                input: "$Information",
                as: "result",
                cond: { $eq: ["$$result.SubjectName", "MySQL"] }
            }
        }
    }},
    { $project: { Information: { SubjectName: 1 } } }
]);
{ "Information": [ { "SubjectName": "MySQL" }, { "SubjectName": "MySQL" } ] }

How It Works

  • $match filters documents containing MySQL subjects
  • $filter extracts only array elements matching the condition
  • Final $project returns only the SubjectName field from filtered results

Conclusion

Use the aggregation pipeline with $match, $filter, and $project to filter array elements and extract specific fields. This approach efficiently handles complex filtering and field selection in nested documents.

Updated on: 2026-03-15T03:20:06+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements