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?
var value = db. collection. count(); and then print(value) or simply value , would give you the count of documents in the collection named collection .
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.
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.
You can do it with $ne operator.
db.items.find({"tags.tag" : {$ne : "completed"}})
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/}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With