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 only get the data of the nested JSON object in MongoDB?
To get the data of the nested JSON object in MongoDB, use findOne() with projection and the $elemMatch operator to filter and return only specific nested array elements.
Syntax
db.collection.findOne(
{ "matchField": "value" },
{ "arrayField": { $elemMatch: { "nestedField": "value" } } }
);
Sample Data
db.demo109.insertOne({
"Name": "Chris",
"Subjects": [
{
"Id": "100",
"Name": "MySQL",
"InstructorDetails": [
{
"Name": "John"
}
]
},
{
"Id": "101",
"Name": "MongoDB",
"InstructorDetails": [
{
"Name": "Mike"
}
]
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e2ee7df9fd5fd66da21447a")
}
Display All Documents
db.demo109.find();
{
"_id": ObjectId("5e2ee7df9fd5fd66da21447a"),
"Name": "Chris",
"Subjects": [
{ "Id": "100", "Name": "MySQL", "InstructorDetails": [ { "Name": "John" } ] },
{ "Id": "101", "Name": "MongoDB", "InstructorDetails": [ { "Name": "Mike" } ] }
]
}
Get Specific Nested Object
To retrieve only the nested object with Id "100" from the Subjects array ?
db.demo109.findOne(
{ "Name": "Chris" },
{ "Subjects": { $elemMatch: { "Id": "100" } } }
);
{
"_id": ObjectId("5e2ee7df9fd5fd66da21447a"),
"Subjects": [
{
"Id": "100",
"Name": "MySQL",
"InstructorDetails": [
{
"Name": "John"
}
]
}
]
}
Key Points
-
$elemMatchreturns only the first matching element from the array - Use projection (second parameter) to limit which fields are returned
- The query condition (first parameter) filters documents, while projection filters fields within matched documents
Conclusion
Use findOne() with $elemMatch in the projection parameter to extract specific nested objects from arrays. This approach filters both the document and the nested array elements efficiently.
Advertisements
