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?
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"}}]})
Use the $not
and $and
operators:
db.collection.find({
$and:[
{"things": {$elemMatch: { "stuff": "banana" }}},
{"things": {$not: {$elemMatch: { "stuff": "apple"}}}}
]
});
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