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 find documents with exactly the same array entries as in a MongoDB query?
To find documents with exactly the same array entries as specified in a MongoDB query, use the $all operator. This operator matches documents where the array field contains all the specified elements, regardless of order.
Syntax
db.collection.find({
"arrayField": { "$all": ["element1", "element2", "element3"] }
});
Sample Data
db.findDocumentExactlySameInArrayDemo.insertMany([
{"TechnicalSubjects": ["C++", "Java", "MongoDB"]},
{"TechnicalSubjects": ["MySQL", "Java", "MongoDB"]},
{"TechnicalSubjects": ["C#", "Python", "MongoDB"]},
{"TechnicalSubjects": ["MySQL", "C", "MongoDB"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd69a5f57806ebf1256f12e"),
ObjectId("5cd69ac057806ebf1256f12f"),
ObjectId("5cd69ad457806ebf1256f130"),
ObjectId("5cd69adf57806ebf1256f131")
]
}
View All Documents
db.findDocumentExactlySameInArrayDemo.find().pretty();
{
"_id": ObjectId("5cd69a5f57806ebf1256f12e"),
"TechnicalSubjects": [
"C++",
"Java",
"MongoDB"
]
}
{
"_id": ObjectId("5cd69ac057806ebf1256f12f"),
"TechnicalSubjects": [
"MySQL",
"Java",
"MongoDB"
]
}
{
"_id": ObjectId("5cd69ad457806ebf1256f130"),
"TechnicalSubjects": [
"C#",
"Python",
"MongoDB"
]
}
{
"_id": ObjectId("5cd69adf57806ebf1256f131"),
"TechnicalSubjects": [
"MySQL",
"C",
"MongoDB"
]
}
Example: Find Documents with Specific Array Elements
Find documents that contain exactly "MySQL", "Java", and "MongoDB" in the TechnicalSubjects array ?
db.findDocumentExactlySameInArrayDemo.find({
"TechnicalSubjects": { "$all": ["MySQL", "Java", "MongoDB"] }
});
{
"_id": ObjectId("5cd69ac057806ebf1256f12f"),
"TechnicalSubjects": ["MySQL", "Java", "MongoDB"]
}
Key Points
- The
$alloperator matches arrays that contain all specified elements - Order of elements in the query does not matter
- The array can contain additional elements beyond those specified
Conclusion
Use $all to find documents where an array field contains all specified values. This operator provides flexible matching regardless of element order within the array.
Advertisements
