Find by _id on an array of objects in MongoDB database?

To find by _id on an array of objects in MongoDB, use the aggregation framework with $unwind and $match operators. This approach is more effective than using find() when working with nested array elements.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $match: { "arrayField.field": "value" } }
]);

Sample Data

db.demo414.insertOne({
    "_id": "110",
    "details": [
        {
            "StudentName": "John",
            "StudentMarks": 56
        },
        {
            "StudentName": "Robert",
            "StudentMarks": 98
        }
    ]
});
{ "acknowledged": true, "insertedId": "110" }

Display Sample Data

db.demo414.find();
{
    "_id": "110",
    "details": [
        { "StudentName": "John", "StudentMarks": 56 },
        { "StudentName": "Robert", "StudentMarks": 98 }
    ]
}

Example: Find Specific Array Element

Find the document with a student having marks of 56 ?

db.demo414.aggregate([
    { $unwind: "$details" },
    { $match: { "details.StudentMarks": 56 } }
]);
{
    "_id": "110",
    "details": { "StudentName": "John", "StudentMarks": 56 }
}

How It Works

  • $unwind deconstructs the array field, creating separate documents for each array element
  • $match filters documents based on the specified condition within the unwound array
  • The result returns the parent document with only the matching array element

Conclusion

Use MongoDB's aggregation pipeline with $unwind and $match to effectively query array elements by their fields. This method provides precise filtering within nested array structures.

Updated on: 2026-03-15T02:54:27+05:30

891 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements