MongoDB asks for an array to exactly match an element, but may not be OK

I have a document in MongoDB that looks like this:

{ users: ["2", "3", "4"] } 

I am trying to query this document by matching an array of users.

 db.things.find( { users: { $all: [ "2", "3", "4" ] } } ) 

This query works, but will also return this document:

 { users: ["2", "3", "4", "5"] } 

The last requirement is to be able to query an array of users with elements out of order, say [ "3", "4", "2" ] in the request, and he will be able to return my first document.

Any help would be greatly appreciated. Thanks in advance.

I also use mongoid if it has an assistant that everyone knows about, but can make a direct mongo request if I need to.

+4
source share
2 answers

You can combine your request with the {users: {$ size: 3}} clause and adjust the size to the number of users for whom you are requesting. This ensures that you get the exact set, not a subset.

If the items are out of order, you may need {users: {$ exists: "1"}} for each and combine those and the $ size clause together.

+10
source

This answer is incorrect.

to request a document for exactly matches in an array, do this.

db.things.insert({a:[1,2]});

db.things.insert({a:[1,2,3]});

db.things.find({a:[1,2]});

returns {a:[1,2]}

Hope this helps - it is so obvious that it is not in the docs

-1
source

All Articles