Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo find documents that do not contain a given value (using $not)

Tags:

mongodb

I have two items in MongoDB:

{'title':'active item',
 'tags':[
        {'tag':'active'},
        {'tag':'anothertag'}
]}
{'title':'completed item',
 'tags':[
        {'tag':'completed'}
]}

It works to find items which are tagged as completed:

db.items.find({'tags.tag':'completed'})
RESULT: [<completed item>]

Now, I want to select all items which are not tagged as completed, so I tried:

db.items.find({$not:{'tags.tag':'completed'}})
DESIRED RESULT: [<active item>]
ACTUAL RESULT: []

But somehow this doesn't return any results. Clearly I misunderstand $not in Mongo, but why? How do I query to find the records that do not contain a given value in their tags?

like image 293
krubo Avatar asked Dec 27 '13 15:12

krubo


People also ask

How do you find the no of documents in a collection MongoDB?

var value = db. collection. count(); and then print(value) or simply value , would give you the count of documents in the collection named collection .

How do I use not condition in MongoDB?

MongoDB provides different types of logical query operators and $not operator is one of them. This operator is used to perform logical NOT operation on the specified operator expressions and select or retrieve only those documents that do not match the given operator expression.

What is the mongo command to find all documents that match search criteria?

To find documents that match a set of selection criteria, call find() with the <criteria> parameter. MongoDB provides various query operators to specify the criteria.


2 Answers

You can do it with $ne operator.

db.items.find({"tags.tag" : {$ne : "completed"}})
like image 109
Parvin Gasimzade Avatar answered Oct 18 '22 06:10

Parvin Gasimzade


The target of the $not operator needs to be an operator-expression, not a field/value object.

So parvin's answer is the easiest way to do this, but just for learning purposes, you can do this with $not by using $not supported expressions like:

db.items.find({tags: {$not: {$elemMatch: {tag: 'completed'}}}})

db.items.find({'tags.tag': {$not: /completed/}})
like image 25
JohnnyHK Avatar answered Oct 18 '22 05:10

JohnnyHK