我有一份具有以下结构的文件:
[{
"items": [
{
"sent_to_lab": 123,
"received_from_lab": 456,
},
{
"sent_to_lab": 123,
},
]
}
... more orders ...
]
我想获取至少一个项符合以下条件的所有订单:
'$and': [
{'items.sent_to_lab': {'$exists': True}},
{'items.received_from_lab': {'$exists': False}},
]
所以在这种情况下,我想返回上述项目,因为items
数组中至少有一个元素符合我的标准。
我怎样才能在mongo中这样做?
答案 0 :(得分:7)
您需要使用$ elemMatch运算符:
db.collection.find({items:
{$elemMatch:{
sent_to_lab:{$exists:true},
received_from_lab:{$exists:false}}
})
这是查询$ elemMatch - 如果你只想取回符合条件的项目(而不是整个文档的整个文档),那么你可以类似地使用投影$ elemMatch算子。