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
Find document that matches same array elements in MongoDB?
To find a document that matches the same array elements in MongoDB, use the $all operator combined with $size. The $all operator selects documents where the array field contains all specified elements, while $size ensures the array has exactly the required number of elements.
Syntax
db.collection.find({
"arrayField": {
$all: ["element1", "element2", "element3"],
$size: numberOfElements
}
});
Sample Data
db.demo543.insertMany([
{id: 101, subject: ["MySQL", "Java", "C", "Python"]},
{id: 102, subject: ["MySQL", "MongoDB", "SQL Server"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e8e1b2f9e5f92834d7f05c9"),
ObjectId("5e8e1b2f9e5f92834d7f05ca")
]
}
Display all documents in the collection ?
db.demo543.find();
{ "_id": ObjectId("5e8e1b2f9e5f92834d7f05c9"), "id": 101, "subject": ["MySQL", "Java", "C", "Python"] }
{ "_id": ObjectId("5e8e1b2f9e5f92834d7f05ca"), "id": 102, "subject": ["MySQL", "MongoDB", "SQL Server"] }
Example
Find the document that contains exactly the same array elements: MySQL, MongoDB, and SQL Server ?
db.demo543.find({
"subject": {
$all: ["MySQL", "MongoDB", "SQL Server"],
$size: 3
}
});
{ "_id": ObjectId("5e8e1b2f9e5f92834d7f05ca"), "id": 102, "subject": ["MySQL", "MongoDB", "SQL Server"] }
Key Points
-
$allensures all specified elements are present in the array -
$sizeensures the array has exactly the specified number of elements - Without
$size, arrays with additional elements would also match
Conclusion
Use $all with $size to find documents with arrays containing exactly the same elements. This combination prevents matching arrays with additional unwanted elements.
Advertisements
