我试图查询我的一个mongodb集合,看起来像这样:
> 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}]}
...
我的目标是列出things
字段包含stuff=banana
但没有stuff=apple
我试过这样的事情:
db.transactions.find({
"things": {
$elemMatch: {
"stuff": "banana",
$ne: {
"stuff": "apple"
}
}
}
)
但它没有用。有什么想法吗?
答案 0 :(得分:7)
以下查询将获取包含things
但不包含stuff=banana
的元素的stuff=apple
字段的所有文档的列表:
db.test.find({"$and":[{"things.stuff":"banana"}, {"things.stuff":{$ne:"apple"}}]})
答案 1 :(得分:1)
使用$not
和$and
运营商:
db.collection.find({
$and:[
{"things": {$elemMatch: { "stuff": "banana" }}},
{"things": {$not: {$elemMatch: { "stuff": "apple"}}}}
]
});
答案 2 :(得分:1)
使用$ in和$ nin来包含和排除
db.transactions.find({
"things.stuff": {
$in: ["banana"],
$nin:["apple"]
}
})