Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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": 91matches documents where the array contains an object with JavaScore = 91 -
Positional operator
"StudentSubjectScore.$": 1projects only the first matching array element -
"_id": 0excludes 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.
Advertisements
