我是 MongoDB 的新手。这是我的 JSON 文档
>
> db.test.find().pretty()
{
"_id" : ObjectId("59ee168f9da785077ed9359d"),
"recordid" : 500,
"metadata" : [
{
"field" : 1,
"values" : [
100,
102,
110,
151,
804
]
},
{
"field" : 2,
"values" : [
201,
202,
151
]
},
{
"field" : 3,
"values" : [
350,
351
]
}
]
}
>
>
我正在尝试在查询中使用 $and 运算符,以便为以下查询检索 0。但是它返回 1。 1 是正确答案,但不是我想要的。
...
...
>
> db.test.find( {
... $and:[
... {"metadata.field": 2},
... {"metadata.values": { $in: [654,804]}},
... {recordid: 500}
... ]
... }
... ).count()
1
>
>
我知道它为什么返回 1 个结果。这是因为 804 的“值”存在于 field: 1
中。
我想要的是查询返回 0 个结果,因为 field: 2
在“值”字段中没有值 654 和 804(它只有 151、201 和 202)。
我做错了什么?
史蒂夫
最佳答案
您可以使用 $elemMatch运算符(operator):
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
例如:
db.test.find({
recordid: 500,
// only match those sub documents in the metadata array which have field=2
// and a score of either 654 or 804
metadata: { $elemMatch: { field: "2", score: { $in: [654, 804] } } }
})
关于json - 查询嵌入式文档数组给出错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46894425/