我的结构如下所示:
{
field1: "somevalue",
name:"xtz",
nested_documents: [
{
x:1,
y:2,
info:[
{name:"sachin",value:"test"},
{name:"sachin", value:"test"}
]
},
{
x:1,
y:3,
info:[
{name:"sachin1",value:"test"},
{name:"sachin2", value:"test"}
]
},
{
x:4,
y:3,
info:[
{name:"sachin",value:"test"},
{name:"sachin", value:"test"}
]
}
]
}
我知道我可以使用以下代码检索第一个数组中存在的元素:
db.test.find({"nested_documents.x": 1},{_id: 0, nested_documents: {$elemMatch: {x: 1}}}
但是,我想对name
属性应用相同的逻辑。我只想检索名称为“sachin”的文档。我尝试的内容如下所示:
db.test.find({"nested_documents.info.name": "sachin"},
{_id: 0, 'nested_documents.info': {$elemMatch: {name: "sachin"}}});
但是Mongo db说它不支持'。投影内的运算符:(。
还有其他方法可以做到这一点吗?(使用命令提示符或代码)
插入文档的命令如下所示:
db.test.insert( {
field1: "somevalue",
name:"xtz",
nested_documents: [
{
x:1,
y:2,
info:[
{name:"sachin",value:"test"},
{name:"sachin", value:"test"}
]
},
{
x:1,
y:3,
info:[
{name:"sachin1",value:"test"},
{name:"sachin2", value:"test"}
]
},
{
x:4,
y:3,
info:[
{name:"sachin",value:"test"},
{name:"sachin", value:"test"}
]
}
]
}
)
我期望输出为:
{ "_id" : ObjectId("5142e0f153cd2aab3a3bae5b"),
"nested_documents" : [
{ "x" : 1, "y" : 2,
"info" : [
{ "name" : "sachin", "value" : "test" },
{ "name" : "sachin", "value" : "test" }
]
},
{ "x" : 4, "y" : 3,
"info" : [ { "name" : "sachin", "value" : "test" },
{ "name" : "sachin", "value" : "test" }
]
}
]
}