MongoDB Find Exact Array Match, but order doesn't matter

I try to find the exact match of the array and get it successfully, but when I try to find the exact array with the values ​​in a different order, then it fails.

Example

 db.coll.insert({"user":"harsh","hobbies":["1","2","3"]}) db.coll.insert({"user":"kaushik","hobbies":["1","2"]}) db.coll.find({"hobbies":["1","2"]}) 

2nd document completed successfully

 db.coll.find({"hobbies":["2","1"]}) 

Show nothing

Please, help

+8
source share
3 answers

the currently accepted answer DOES NOT provide an exact match in your array, only the size is identical and that the array uses at least one element with an array of queries.

For example, request

 db.coll.find({ "hobbies": { "$size" : 2, "$in": [ "2", "1", "5", "hamburger" ] } }); 

will still return kaushik to the user in this case.

What you need to do for an exact match is to combine $size with $all , for example:

 db.coll.find({ "hobbies": { "$size" : 2, "$all": [ "2", "1" ] } }); 

But keep in mind that this can be a very expensive operation, depending on your amount and data structure. Since MongoDB keeps the order of the inserted arrays in a stable state, you might be better off if the arrays are sorted in order when pasted into the database, so you can rely on the static order when querying.

+20
source

According to the field of the array, it is Mongo that provides the $eq operator, which can be controlled through the array as well as the value.

 db.collection.find({ "hobbies": {$eq: [ "singing", "Music" ] }}); 

Also $eq checks the order in which you specify the elements.

If you use the request below:

 db.coll.find({ "hobbies": { "$size" : 2, "$all": [ "2", "1" ] } }); 

Then the exact match will not be returned. Suppose you requested:

 db.coll.find({ "hobbies": { "$size" : 2, "$all": [ "2", "2" ] } }); 

This query will return all documents having element 2 and having size 2 (for example, it will also return a document with hobies :[2,1] ).

+10
source

This query will find the exact array in any order.

 let query = {$or: [ {hobbies:{$eq:["1","2"]}}, {hobbies:{$eq:["2","1"]}} ]}; db.coll.find(query) 
0
source

Source: https://habr.com/ru/post/985603/


All Articles