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 from part of object in an array with MongoDB
To query from part of object in an array with MongoDB, use dot notation to access nested array fields and the $all operator to match documents where an array field contains all specified values.
Syntax
db.collection.find({ "arrayField.nestedField": { $all: ["value1", "value2"] } });
Sample Data
Let us create a collection with documents containing user details in arrays ?
db.demo25.insertMany([
{
"Details": [
{
"UserId": "Carol101",
"UserName": "Carol"
},
{
"UserId": "David102",
"UserName": "David"
}
]
},
{
"Details": [
{
"UserId": "Chris101",
"UserName": "Chris"
},
{
"UserId": "Mike102",
"UserName": "Mike"
}
]
}
]);
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("5e14c86e22d07d3b95082e77"),
"1": ObjectId("5e14c86f22d07d3b95082e78")
}
}
Display all documents from the collection ?
db.demo25.find();
{ "_id": ObjectId("5e14c86e22d07d3b95082e77"), "Details": [ { "UserId": "Carol101", "UserName": "Carol" }, { "UserId": "David102", "UserName": "David" } ] }
{ "_id": ObjectId("5e14c86f22d07d3b95082e78"), "Details": [ { "UserId": "Chris101", "UserName": "Chris" }, { "UserId": "Mike102", "UserName": "Mike" } ] }
Example: Query with $all Operator
Find the document that contains both "Carol101" and "David102" in the Details array ?
db.demo25.findOne({ "Details.UserId": { $all: ["Carol101", "David102"] } });
{
"_id": ObjectId("5e14c86e22d07d3b95082e77"),
"Details": [
{
"UserId": "Carol101",
"UserName": "Carol"
},
{
"UserId": "David102",
"UserName": "David"
}
]
}
How It Works
- Dot notation "Details.UserId" accesses the UserId field within the Details array objects
-
$alloperator ensures the array contains ALL specified values, not just one -
findOne()returns only the first matching document
Conclusion
Use dot notation with $all to query nested array fields in MongoDB. This approach effectively matches documents where array elements contain all specified values.
Advertisements
