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 get all docs which contain another doc in an array with MongoDB?
To get all documents which contain another document in an array, use dot notation with the find() method in MongoDB. This allows you to query nested fields within array elements.
Syntax
db.collection.find({"arrayField.nestedField": "value"});
Sample Data
Let us create a collection with documents containing nested objects in arrays ?
db.demo465.insertMany([
{
id: 101,
details: [
{
Name: "Chris",
Info: {
Subject: "MongoDB",
Marks: 67
}
},
{
Name: "David",
Info: {
Subject: "MySQL",
Marks: 78
}
}
]
},
{
id: 102,
details: [
{
Name: "Bob",
Info: {
Subject: "Java",
Marks: 45
}
},
{
Name: "Carol",
Info: {
Subject: "C",
Marks: 67
}
}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e80421bb0f3fa88e2279061"),
ObjectId("5e80421cb0f3fa88e2279062")
]
}
Display All Documents
db.demo465.find();
{
"_id": ObjectId("5e80421bb0f3fa88e2279061"),
"id": 101,
"details": [
{ "Name": "Chris", "Info": { "Subject": "MongoDB", "Marks": 67 } },
{ "Name": "David", "Info": { "Subject": "MySQL", "Marks": 78 } }
]
}
{
"_id": ObjectId("5e80421cb0f3fa88e2279062"),
"id": 102,
"details": [
{ "Name": "Bob", "Info": { "Subject": "Java", "Marks": 45 } },
{ "Name": "Carol", "Info": { "Subject": "C", "Marks": 67 } }
]
}
Example: Query Documents Containing Specific Nested Document
Find all documents where the details array contains a document with Name "Bob" ?
db.demo465.find({"details.Name": "Bob"});
{
"_id": ObjectId("5e80421cb0f3fa88e2279062"),
"id": 102,
"details": [
{ "Name": "Bob", "Info": { "Subject": "Java", "Marks": 45 } },
{ "Name": "Carol", "Info": { "Subject": "C", "Marks": 67 } }
]
}
Key Points
- Use
arrayField.nestedFieldsyntax to query nested documents in arrays - MongoDB automatically searches through all array elements for matching values
- Returns the entire parent document when a match is found
Conclusion
Dot notation provides an efficient way to query documents containing specific nested objects in arrays. Use "arrayField.nestedField": value syntax to find documents where array elements match your criteria.
Advertisements
