5

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?

user1534422
  • 511
  • 1
  • 8
  • 14

3 Answers3

8

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"}}]})
Anand Jayabalan
  • 12,294
  • 5
  • 41
  • 52
3

Use the $not and $and operators:

db.collection.find({

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

});
Roberto
  • 8,586
  • 3
  • 42
  • 53
3

Use $in and $nin to include and exclude

db.transactions.find({
  "things.stuff": {
    $in: ["banana"], 
    $nin:["apple"]
  }
})
Shreyance Jain
  • 914
  • 7
  • 12