3

I'm developing an app with mongoose to access MongoDB.

And what I'm trying to achieve is to make a query and discar some documents by id.

User.find({})
    .where('price').lt(upperLimit)
    ....
    .exec(function(err, users) {
      //
    });

The point is I want to discard some users that I know before doing the query. Any ideas?. I don't want to post-process users collections and filter.

Thanks!

2 Answers 2

3

You can use the $nin operator to exclude an array of _id values:

User.find({})
  .where('price').lt(upperLimit)
  .nin('_id', idsToExclude)
  ....
  .exec(function(err, users) {
    //
  });
Sign up to request clarification or add additional context in comments.

2 Comments

I would suggest not using the $nin operator if possible and rather use the $ne operator as $nin is not capable of using an index (indexes are only inclusive not exclusive) thus forcing a table scan across all documents.
@christkv Actually, neither $nin nor $ne use indexes effectively (see here), but as @nutlike noted in his comments, $ne doesn't work in this case. As long as another query term is included first (in this case price) the $nin only needs to scan through the docs with the matching price, not the whole collection.
2

You could use the $ne operator:

User.find({"_id":{"$ne":<IdToExclude>}}). …

4 Comments

Ok, but if its, an array of objects?
For arrays you could use the $all operator. User.find({"ids":{"$ne":{"$all":[<FirstIdToExclude>,<SecondIdToExclude>,…]}}}). …
I think JohnnyHK approach is the better one but could you let us know if this one works too?
I just checked it myself and it does not seem to work, sorry! Stick to JohnnyHK's answer for arrays.

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.