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 get specific list of names from documents where the value of a field is an array
To get specific list of names from documents where the value of a field is an array, use the $all operator. The $all operator selects documents where the array field contains all the specified elements.
Syntax
db.collection.find({
arrayField: {
$all: [ "element1", "element2", ... ]
}
});
Sample Data
Let us create a collection with documents containing arrays of names ?
db.demo642.insertMany([
{
_id: 1,
ListOfNames: ["Robert", "John"]
},
{
_id: 2,
ListOfNames: ["Robert", "Chris"]
}
]);
{
"acknowledged": true,
"insertedIds": {
"0": 1,
"1": 2
}
}
Display all documents from the collection ?
db.demo642.find();
{ "_id": 1, "ListOfNames": [ "Robert", "John" ] }
{ "_id": 2, "ListOfNames": [ "Robert", "Chris" ] }
Example: Find Documents Containing Specific Names
Find documents where ListOfNames contains both "Chris" and "Robert" ?
db.demo642.find({
ListOfNames: {
$all: [ "Chris", "Robert" ]
}
});
{ "_id": 2, "ListOfNames": [ "Robert", "Chris" ] }
Key Points
- The
$alloperator requires all specified elements to be present in the array. - Order of elements in the
$allarray doesn't matter. - Only document with _id: 2 matches because it contains both "Chris" and "Robert".
Conclusion
Use the $all operator to query documents where an array field contains all specified values. This is useful for finding documents that match multiple criteria within array fields.
Advertisements
