How to retrieve a nested object in MongoDB?

To retrieve a nested object in MongoDB, use the $ positional operator with dot notation to match specific elements within arrays or embedded documents.

Syntax

db.collection.find(
    {"arrayField.nestedField": value},
    {"arrayField.$": 1}
)

Sample Data

Let us first create a collection with documents ?

db.queryNestedObject.insertOne({
    "StudentName": "James",
    "StudentSubjectScore": [
        {"StudentMongoDBScore": 98},
        {"StudentCScore": 92},
        {"StudentJavaScore": 91}
    ]
})
{
    "acknowledged": true,
    "insertedId": ObjectId("5ccf49a9dceb9a92e6aa1962")
}

View Complete Document

Display all documents from the collection ?

db.queryNestedObject.find().pretty()
{
    "_id": ObjectId("5ccf49a9dceb9a92e6aa1962"),
    "StudentName": "James",
    "StudentSubjectScore": [
        {
            "StudentMongoDBScore": 98
        },
        {
            "StudentCScore": 92
        },
        {
            "StudentJavaScore": 91
        }
    ]
}

Retrieve Specific Nested Object

Query to retrieve the nested object containing Java score ?

db.queryNestedObject.find(
    {"StudentSubjectScore.StudentJavaScore": 91},
    {"StudentSubjectScore.$": 1, "_id": 0}
)
{
    "StudentSubjectScore": [
        {"StudentJavaScore": 91}
    ]
}

How It Works

  • Dot notation "StudentSubjectScore.StudentJavaScore": 91 matches documents where the array contains an object with JavaScore = 91
  • Positional operator "StudentSubjectScore.$": 1 projects only the first matching array element
  • "_id": 0 excludes the document ID from results

Conclusion

Use dot notation in the query condition and the $ positional operator in projection to retrieve specific nested objects from MongoDB arrays. This returns only the first matching array element that satisfies the condition.

Updated on: 2026-03-15T00:59:46+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements