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 ] }