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 to find data from an array inside an object?
To find data from an array inside an object in MongoDB, use dot notation to navigate through the nested object structure and target the specific array field.
Syntax
db.collection.find({"objectField.arrayField": "searchValue"});
Sample Data
Let us first create a collection with documents ?
db.findDataDemo.insertMany([
{
"CustomerName": "John",
"CustomerDetails": {
"CountryName": ["AUS"],
"isMarried": [false]
}
},
{
"CustomerName": "Carol",
"CustomerDetails": {
"CountryName": ["UK"],
"isMarried": [true]
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cefa5eeef71edecf6a1f6a5"),
ObjectId("5cefa60aef71edecf6a1f6a6")
]
}
View Sample Data
db.findDataDemo.find().pretty();
{
"_id": ObjectId("5cefa5eeef71edecf6a1f6a5"),
"CustomerName": "John",
"CustomerDetails": {
"CountryName": ["AUS"],
"isMarried": [false]
}
}
{
"_id": ObjectId("5cefa60aef71edecf6a1f6a6"),
"CustomerName": "Carol",
"CustomerDetails": {
"CountryName": ["UK"],
"isMarried": [true]
}
}
Example: Query Array Inside Object
Find documents where the CountryName array contains "UK" ?
db.findDataDemo.find({"CustomerDetails.CountryName": "UK"});
{
"_id": ObjectId("5cefa60aef71edecf6a1f6a6"),
"CustomerName": "Carol",
"CustomerDetails": {
"CountryName": ["UK"],
"isMarried": [true]
}
}
Key Points
- Use dot notation to access nested fields:
"object.array" - MongoDB automatically searches within array elements for matching values
- No special array operators needed for simple value matching
Conclusion
Use dot notation with the format "objectField.arrayField" to query arrays nested inside objects. MongoDB will automatically search through the array elements to find matching documents.
Advertisements
