Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Find Exact Array Match but order doesn't matter

I am querying for finding exact array match and retrieved it successfully but when I try to find out the exact array with values in different order then it get 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 Retrieved Successfully

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

Showing Nothing

Please help

like image 229
Harsh Kanakhara Avatar asked Apr 21 '15 13:04

Harsh Kanakhara


1 Answers

The currently accepted answer does NOT ensure an exact match on your array, just that the size is identical and that the array shares at least one item with the query array.

For example, the query

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

would still return the user kaushik in that case.

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

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

But be aware that this can be a very expensive operation, depending on your amount and structure of data. Since MongoDB keeps the order of inserted arrays stable, you might fare better with ensuring arrays to be in a sorted order when inserting to the DB, so that you may rely on a static order when querying.

like image 67
kasoban Avatar answered Nov 24 '22 06:11

kasoban