Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 778
scrineym Avatar asked Jan 17 '26 03:01

scrineym


2 Answers

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!!

like image 78
scrineym Avatar answered Jan 19 '26 17:01

scrineym


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

like image 42
Mario Trucco Avatar answered Jan 19 '26 18:01

Mario Trucco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!