Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb - Array containing element and not containing another one

I'm trying to query one of my mongodb collection that looks like this:

> db.collection.find()
{name: "foo", things: [{stuff:"banana", value: 1}, {stuff:"apple", value: 2}, {stuff:"strawberry", value: 3}]}
{name: "bar", things: [{stuff:"banana", value: 4}, {stuff:"pear", value: 5}]}
...

My goal is to list all the object that have the things field containing an element with stuff=banana but no stuff=apple

I tried something like this:

db.transactions.find({
  "things": {
    $elemMatch: {
      "stuff": "banana", 
      $ne: {
        "stuff": "apple"
      }
    }
  }
)

But it's not working. Any ideas?

like image 691
user1534422 Avatar asked Dec 16 '22 00:12

user1534422


2 Answers

The below query will get the list of all documents that have the things field containing an element with stuff=banana but no stuff=apple:

db.test.find({"$and":[{"things.stuff":"banana"}, {"things.stuff":{$ne:"apple"}}]})
like image 182
Anand Jayabalan Avatar answered Apr 30 '23 03:04

Anand Jayabalan


Use the $not and $and operators:

db.collection.find({

   $and:[
    {"things": {$elemMatch: {  "stuff": "banana"  }}},
    {"things": {$not: {$elemMatch: { "stuff": "apple"}}}}
  ]

});
like image 44
Roberto Avatar answered Apr 30 '23 01:04

Roberto