How to find a certain element in the MongoDB embedded document?

To find a certain element in a MongoDB embedded document, use the aggregation pipeline with $unwind to flatten the array, $match to filter specific elements, and $project to select desired fields.

Syntax

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

Sample Data

db.demo744.insertOne({
    studentInformation: [
        {
            studentName: "Robert",
            grade: "A"
        },
        {
            studentName: "Bob",
            grade: "C"
        },
        {
            studentName: "John",
            grade: "B"
        },
        {
            studentName: "Sam",
            grade: "A"
        }
    ]
})
{
    "acknowledged": true,
    "insertedId": ObjectId("5ead928a57bb72a10bcf0684")
}

View Sample Data

db.demo744.find()
{
    "_id": ObjectId("5ead928a57bb72a10bcf0684"),
    "studentInformation": [
        { "studentName": "Robert", "grade": "A" },
        { "studentName": "Bob", "grade": "C" },
        { "studentName": "John", "grade": "B" },
        { "studentName": "Sam", "grade": "A" }
    ]
}

Example: Find Students with Grade "A"

db.demo744.aggregate([
    { $unwind: "$studentInformation" },
    { $match: { "studentInformation.grade": "A" } },
    { $project: { "studentInformation.studentName": 1 } }
])
{ "_id": ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation": { "studentName": "Robert" } }
{ "_id": ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation": { "studentName": "Sam" } }

How It Works

  • $unwind creates separate documents for each array element
  • $match filters documents based on embedded field conditions
  • $project selects only the required fields from the results

Conclusion

Use aggregation pipeline with $unwind, $match, and $project to find and extract specific elements from embedded documents. This approach effectively searches within array fields and returns only matching elements.

Updated on: 2026-03-15T03:54:47+05:30

238 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements