我有一个对象数组,我想检查是否有一个对象与多个属性匹配。我尝试过使用$in
and $and
但它并没有按照我想要的方式工作。
这是我当前的实现。 https://mongoplayground.net/p/dEQp2Q4DW0j
我有一个像这样的数组
"choices": [
{
"name": "choiceA",
"id": 0,
"l": "k"
},
{
"name": "choiceB",
"id": 1,
"l": "j"
},
{
"name": "choiceC",
"id": 2,
"l": "l"
}
]
我正在尝试编写聚合代码来检查是否存在包含两者的对象"id":2
and "l":"j"
特性。我当前的实现检查是否存在包含第一个属性的对象,然后检查是否存在包含第二个属性的对象。
我怎样才能得到我想要的结果?
下面,请参阅我的聚合查询。完整的代码是here https://mongoplayground.net/p/dEQp2Q4DW0j
db.poll.aggregate([
{
"$match": {
"_id": 100
}
},
{
$project: {
numberOfVotes: {
$and: [
{
$in: [
2,
"$choices.id"
]
},
{
$in: [
"j",
"$choices.l"
]
}
]
},
}
}
])
上面的查询返回 true,但数组中没有对象这两个属性id:2
and "l":"J"
。我知道代码按预期工作。我怎样才能得到我想要的结果?