scrineym
scrineym

Reputation: 759

Mongo get inverse of query

Hello I'm having trouble trying to understand how to write this query

My collection is a series of entries like this:

{
  id:1,
  name:"peter",
  number:3
 }

I want to be able to write a query which will return all items except for documents where the name='peter' and number=3

I know I can write something like:

db.test.find({$and:[{'name':'peter'},{'num':3}]})

to return all matching items, but is there any way of rewriting this query to return everything but the matching elements?

Upvotes: 3

Views: 2261

Answers (3)

Mario Trucco
Mario Trucco

Reputation: 2011

You can use a trick involving $nor with only one statement. Your only statement is then the original query. This works because $nor means that all conditions must be false; if you have only one condition, you get the negation.

So try:

db.test.find({$nor:[{$and:[{'name':'peter'},{'num':3}]}]})

I think this is nice because it's the negation of your original query exactly as it was

Upvotes: 3

Raunak Jhawar
Raunak Jhawar

Reputation: 1651

You can use the $ne operator to test for not equality:

find({$and: [{name: {$ne: peter}}, {num: {$ne: 2}}]})

Upvotes: -1

scrineym
scrineym

Reputation: 759

The $not operator requires a field to be bound to , but in this case it wont work. Basically I had to rethink my query, using DeMorgan's law

¬(A^B) = ¬(A)V¬(B)

NOT (A AND B) = NOT(A) OR NOT(B) so my query is

db.test.find({ $or:[{name:{$not:{$eq:'peter'}}},{num:{$not:{$eq:3}}}]});

Boolean algebra to the rescue!!

Upvotes: 4

Related Questions