Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find documents with exactly the same array entries as in a MongoDB query?
For this, use the $all operator. Let us first create a collection with documents −
>db.findDocumentExactlySameInArrayDemo.insertOne({"TechnicalSubjects":["C++","Java","MongoDB"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd69a5f57806ebf1256f12e")
}
>db.findDocumentExactlySameInArrayDemo.insertOne({"TechnicalSubjects":["MySQL","Java","MongoDB"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd69ac057806ebf1256f12f")
}
>db.findDocumentExactlySameInArrayDemo.insertOne({"TechnicalSubjects":["C#","Python","MongoDB"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd69ad457806ebf1256f130")
}
>db.findDocumentExactlySameInArrayDemo.insertOne({"TechnicalSubjects":["MySQL","C","MongoDB"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd69adf57806ebf1256f131")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.findDocumentExactlySameInArrayDemo.find().pretty();
This will produce the following output −
{
"_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"
]
}
Following is the query to find documents with exactly the same array entries as in a query −
> db.findDocumentExactlySameInArrayDemo.find({"TechnicalSubjects": { "$all": ["MySQL","Java","MongoDB"] }});
This will produce the following output −
{ "_id" : ObjectId("5cd69ac057806ebf1256f12f"), "TechnicalSubjects" : [ "MySQL", "Java", "MongoDB" ] }Advertisements