我有一个嵌套数组的文档,我无法弄清楚如何从一个字段中选择。
我想选择“组件”具有“桅杆”的所有文档。
我试过了。
db.sites.find({“components”:“mast”})。pretty();
db.sites.find({“components。$”:“mast”})。pretty();
db.sites.find({“components。$。$”:“mast”})。pretty();
db.sites.find({“components。$。$。mast”:{$ exists:true}})。pretty();
db.sites.find({“components。$。mast”:{$ exists:true}})。pretty();
db.sites.find({“components.mast”:{$ exists:true}})。pretty();
和一堆其他失败的尝试。
{
"_id" : ObjectId("23456yujbvfdfg"),
"d": 1234567,
"components" : [
[
"mast",
{
"foo":"bar"
}
],
[
"commsbox",
{
"BLARN": "bAAA"
}
]
]
}
我的尝试只返回空白结果。
如果您将组件维护为数组,则查询应该如下所示
db.test.find({ "components": { $elemMatch: { $elemMatch: {$eq:"mast"} } }})
我已根据您共享的架构发布了解决方案,但我确信架构需要更改
你可以使用$elemMatch
db.sites.find(
{ "components": { $elemMatch: { $elemMatch: {$eq:"mast"} } }}
)
这应该工作
db.sites.find({
"components": {
$elemMatch: {
$elemMatch: { $in: ['mast'] }
}
}
})