6

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It is surprising that model.find({'tags': {$all: []}}) does not return all documents (assuming tags exists as an empty array in each document).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.