我有这个文件
<
并且只想提取{
"_id" : ObjectId("6afda532e9a0e3838537c71a"),
"VersionId" : 0,
"NodeId" : [
{
"NodeId" : 0,
"Host" : "127.0.0.1",
"DatabaseName" : "NodeId0",
"Collection" : [
{
"CollectionId" : 0,
"CollectionName" : "Codice0"
},
{
"CollectionId" : 1,
"CollectionName" : "Codice1"
}
]
},
{
"NodeId" : 1,
"Host" : "127.0.0.2",
"DatabaseName" : "NodeId1",
"Collection" : [
{
"CollectionId" : 1,
"CollectionName" : "Codice1"
}
]
}
]
}
的1个字段和nodeId
的1个字段,是否可能?
返回的文档应具有以下结构:
CollectionId
我尝试了这个查询,没有结果:
{
VersionId: 0,
NodeId: {
NodeId: 0,
Collection: {
CollectionId: 0,
CollectionName: Codice0
}
}
}
答案 0 :(得分:2)
如果您使用&#34; VersionId&#34;或者使用_Id然后结果如下:
db.getCollection('a').aggregate([
{$unwind: '$NodeId'},
{$unwind: '$NodeId.Collection'},
{$match: {"_id" : ObjectId("5846b47c8254f4cad9acadce"), "VersionId" : 0, "NodeId.NodeId": 0, "NodeId.Collection.CollectionId": 0}}
])
输出如下数据:
{
"_id" : ObjectId("5846b47c8254f4cad9acadce"),
"VersionId" : 0,
"NodeId" : {
"NodeId" : 0,
"Host" : "127.0.0.1",
"DatabaseName" : "NodeId0",
"Collection" : {
"CollectionId" : 0,
"CollectionName" : "Codice0"
}
}
}
答案 1 :(得分:2)
您可以尝试以下内容。利用 $map 投影所需字段,并使用 $filter 进行过滤匹配Node和Collection以及 $arrayElemAt ,将数组更改为object以匹配预期的输出格式。
aggregate([{
$match: {
"VersionId": 0
}
}, {
$project: {
NodeId: {
$arrayElemAt: [{
$map: {
input: {
$filter: {
input: "$NodeId",
as: "prova",
cond: {
$eq: ["$$prova.NodeId", 0]
}
}
},
as: "nd",
in: {
"NodeId": "$$nd.NodeId",
"Collection": {
$arrayElemAt: [{
$filter: {
input: "$$nd.Collection",
as: "proval",
cond: {
$eq: ["$$proval.CollectionId", 0]
}
}
}, 0]
}
}
}
}, 0]
},
_id: 0
}
}])