afterxleep
afterxleep

Reputation: 642

MongoDB: $all with empty array...

I'm running a query on a collection with documents like these.

{"name": "Daniel", "tags": ["person", "owner", "father"]},
{"name": "Jane", "tags": ["person", "owner", "mother"]},
{"name": "Jimmy", "tags": ["person", "owner", "son"]}

Now, if I want to find all documents matching the tags person AND owner I would do something like this

var match = ['person', 'owner'];
model.find({'tags': {$all: match}});

Now I need to do the following:

  1. When match has values, return all document matching those (This is done)
  2. When match is empty [ ], return all documents.

What's the most efficient way to do that in a single query?

Thanks in advance,

D

Upvotes: 6

Views: 2093

Answers (1)

BatScream
BatScream

Reputation: 19700

I would suggest you to add the condition in your application layer, and keep your query that gets executed on the server very simple.

  • If the match array has one or more elements, add a query field to your query condition, else execute an empty condition which would return you all the documents.

snippet:

var match = ['person', 'owner'];
var condition = {};
if(match.length > 0){
   condition["tags"] = {$all:match};
}
db.model.find(condition);

Having said this, with the $all operator, it is not possible to achieve both the conditions in a single query.

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.

Upvotes: 2

Related Questions