(请注意:尽管this question的标题相似,但实际上与过滤相比,与投影有关的更多;我无法理解它如何适用于我的用例。
如果相关,那么我先向您道歉:))
给出以下文档结构:
{
"id" : "1",
"groups" : [
{
"name" : "group1.1",
"contacts" : [
{ "localId" : "c1.1", "address" : "some address 1" },
{ "localId" : "c1.2", "address" : "some address 2" },
{ "localId" : "c1.3", "address" : "some address 3" }
]
},
{
"name" : "group1.2",
"contacts" : [
{ "localId" : "c1.1", "address" : "some address 1" },
{ "localId" : "c1.4", "address" : "some address 3" }
]
}
]
},
{
"id" : "2",
"groups" : [
{
"name" : "group2.1",
"contacts" : [
{ "localId" : "c2.1", "address" : "some address 1" },
{ "localId" : "c2.2", "address" : "some address 2" },
{ "localId" : "c2.3", "address" : "some address 3" }
]
},
{
"name" : "group2.2",
"contacts" : [
{ "localId" : "c2.1", "address" : "some address 1" },
{ "localId" : "c2.3", "address" : "some address 3" }
]
}
]
}
如何创建投影以仅返回{em> contacts
数组中的groups
数组以及这些数组中的 all 元素? br />
我仍然想保持原始结构(即数组不应展平)
即要求的输出为:
{
"groups" : [
{
"contacts" : [
{ "localId" : "c1.1", "address" : "some address 1" },
{ "localId" : "c1.2", "address" : "some address 2" },
{ "localId" : "c1.3", "address" : "some address 3" }
]
},
{
"contacts" : [
{ "localId" : "c1.1", "address" : "some address 1" },
{ "localId" : "c1.4", "address" : "some address 3" }
]
}
]
},
{
"groups" : [
{
"contacts" : [
{ "localId" : "c2.1", "address" : "some address 1" },
{ "localId" : "c2.2", "address" : "some address 2" },
{ "localId" : "c2.3", "address" : "some address 3" }
]
},
{
"contacts" : [
{ "localId" : "c2.1", "address" : "some address 1" },
{ "localId" : "c2.3", "address" : "some address 3" }
]
}
]
}
对于非数组属性,类似{'groups.name': 1}
的东西可以正常工作。
我也尝试过类似db.collection.findOne({}, { 'groups.contacts': 1 })
的方法来尝试获取联系人,但这根本没有返回contacts
字段。.