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
MongoDB query in object of arrays
To query arrays within nested objects in MongoDB, use dot notation to navigate through the object hierarchy and target specific array fields. MongoDB will match documents where the array contains the specified value.
Syntax
db.collection.find({ "object.nestedObject.arrayField": "value" });
Sample Data
db.demo194.insertMany([
{
"_id": 101,
"details": {
"otherDetails": {
"List1": ["MongoDB", "MySQL"],
"List2": ["Java"],
"List3": ["MongoDB", "C"]
}
}
},
{
"_id": 102,
"details": {
"otherDetails": {
"List1": ["Java", "C"],
"List2": ["C++"],
"List3": ["Python", "Spring"]
}
}
}
]);
{ "acknowledged": true, "insertedIds": { "0": 101, "1": 102 } }
Example: Query Array in Nested Object
Find documents where List1 contains "MongoDB" ?
db.demo194.find({ "details.otherDetails.List1": "MongoDB" });
{ "_id": 101, "details": { "otherDetails": { "List1": [ "MongoDB", "MySQL" ], "List2": [ "Java" ], "List3": [ "MongoDB", "C" ] } } }
Additional Query Examples
Query Different Array Field
db.demo194.find({ "details.otherDetails.List2": "C++" });
{ "_id": 102, "details": { "otherDetails": { "List1": [ "Java", "C" ], "List2": [ "C++" ], "List3": [ "Python", "Spring" ] } } }
Key Points
- Use dot notation to traverse nested object structures:
object.nestedObject.arrayField - MongoDB automatically searches for the value within the array − no special array operators needed
- Queries match documents where any array element equals the specified value
Conclusion
Querying arrays in nested objects requires dot notation to navigate the object hierarchy. MongoDB's implicit array matching makes it simple to find documents containing specific values in deeply nested arrays.
Advertisements
