- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 exact Array Match with values in different order using MongoDB?
To find exact array match with values in different order, you can use $all operator. Let us create a collection with documents. Following is the query
>db.exactMatchArrayDemo.insertOne({"StudentName":"David","StudentAge":22,"StudentGameScores":[45,78,98]}); { "acknowledged" : true, "insertedId" : ObjectId("5c9c94702d6669774125246c") } >db.exactMatchArrayDemo.insertOne({"StudentName":"Chris","StudentAge":23,"StudentGameScores":[45,78]}); { "acknowledged" : true, "insertedId" : ObjectId("5c9c94a42d6669774125246d") }
Following is the query to display all documents from a collection with the help of find() method
> db.exactMatchArrayDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9c94702d6669774125246c"), "StudentName" : "David", "StudentAge" : 22, "StudentGameScores" : [ 45, 78, 98 ] } { "_id" : ObjectId("5c9c94a42d6669774125246d"), "StudentName" : "Chris", "StudentAge" : 23, "StudentGameScores" : [ 45, 78 ] }
Following is the query to find exact array match
> db.exactMatchArrayDemo.find({ "StudentGameScores": { "$size" : 2, "$all": [ 78, 45 ] } }).pretty();
This will produce the following output
{ "_id" : ObjectId("5c9c94a42d6669774125246d"), "StudentName" : "Chris", "StudentAge" : 23, "StudentGameScores" : [ 45, 78 ] }
Following is the query to find exact array match but order does not matter. We have set a different size to get the field “StudentGameScores” with 3 values
> db.exactMatchArrayDemo.find({ "StudentGameScores": { "$size" : 3, "$all": [ 78, 45 ] } }).pretty();
This will produce the following output
{ "_id" : ObjectId("5c9c94702d6669774125246c"), "StudentName" : "David", "StudentAge" : 22, "StudentGameScores" : [ 45, 78, 98 ] }
Advertisements