MongoDB query to find and return subdocument with criteria?

To find and return subdocuments that match specific criteria in MongoDB, use the aggregation pipeline with $match to filter documents and $filter to return only matching subdocuments from arrays.

Syntax

db.collection.aggregate([
    { $match: { "fieldName": "value" } },
    { 
        $addFields: {
            "arrayField": {
                $filter: {
                    input: "$arrayField",
                    cond: { $eq: ["$$this.subField", "criteria"] }
                }
            }
        }
    }
])

Sample Data

db.demo345.insertOne({
    "UserName": "Robert",
    "UserDetails": [
        {
            "isMarried": false,
            "CountryName": "US"
        },
        {
            "isMarried": true,
            "CountryName": "UK"
        },
        {
            "isMarried": false,
            "CountryName": "AUS"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e5404fdf8647eb59e5620ac")
}

Display all documents from the collection ?

db.demo345.find();
{
    "_id": ObjectId("5e5404fdf8647eb59e5620ac"), 
    "UserName": "Robert", 
    "UserDetails": [
        { "isMarried": false, "CountryName": "US" },
        { "isMarried": true, "CountryName": "UK" },
        { "isMarried": false, "CountryName": "AUS" }
    ]
}

Example: Return Subdocuments with Criteria

Find and return only subdocuments where isMarried is true ?

db.demo345.aggregate([
    {
        $match: { UserName: "Robert" }
    },
    {
        $addFields: {
            UserDetails: {
                $filter: {
                    input: "$UserDetails",
                    cond: {
                        $eq: ["$$this.isMarried", true]
                    }
                }
            }
        }
    }
]);
{
    "_id": ObjectId("5e5404fdf8647eb59e5620ac"), 
    "UserName": "Robert", 
    "UserDetails": [
        { "isMarried": true, "CountryName": "UK" }
    ]
}

Key Points

  • $match filters the parent documents first
  • $filter returns only array elements that match the condition
  • $$this refers to each element in the input array
  • $addFields replaces the original array with the filtered results

Conclusion

Use MongoDB's aggregation pipeline with $filter to return specific subdocuments based on criteria. This approach efficiently filters nested arrays while preserving the document structure.

Updated on: 2026-03-15T02:34:14+05:30

603 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements