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
Querying on an array of objects for specific nested documents with MongoDB?
To query on an array of objects for nested documents in MongoDB, use the find() method with the $elemMatch operator in projection to return only matching array elements.
Syntax
db.collection.find(
{},
{
arrayField: {
$elemMatch: { condition }
}
}
);
Sample Data
db.demo763.insertOne({
_id: 1,
CountryName: "US",
"studentInformation": [
{
StudentName: "Chris"
},
{
StudentName: "David",
StudentAge: 22
}
]
});
{ "acknowledged": true, "insertedId": 1 }
Display all documents from a collection with the help of find() method ?
db.demo763.find();
{ "_id": 1, "CountryName": "US", "studentInformation": [ { "StudentName": "Chris" }, { "StudentName": "David", "StudentAge": 22 } ] }
Example: Query for Students with Age Field
Following is how to query an array of objects to fetch specific nested documents ?
db.demo763.find({},
{
studentInformation: {
$elemMatch: {
StudentAge: {
$exists: true
}
}
}
});
{ "_id": 1, "studentInformation": [ { "StudentName": "David", "StudentAge": 22 } ] }
Key Points
-
$elemMatchin projection returns only the first matching array element -
$exists: truefilters for documents where the specified field exists - Use empty query
{}to match all documents, then filter array elements in projection
Conclusion
Use $elemMatch in projection to query and return specific nested documents from arrays. This approach filters array elements based on conditions while preserving the document structure.
Advertisements
