提前感谢您查看此内容... 我的文件:
{
"_id" : { "$oid" : "550b2873e9dd90068070c31b" },
"dateCreated" : { "$date" : 1426794611867 },
"sections" : [
{
"_id" : { "$oid" : "550b2881e9dd90068070c31d" },
"index" : 0,
"name" : "Section 2",
"slides" : [
{
"_id" : { "$oid" : "550b288ce9dd90068070c321" },
"index" : 0,
"status" : "Unpublished"
},
{
"_id" : { "$oid" : "55105b87e9dd90068033ba4a" },
"index" : 1,
"status" : "Published"
}
]
},
{
"_id" : { "$oid" : "550b287ae9dd90068070c31c" },
"index" : 1,
"name" : "Section 1",
"slides" : [
{
"_id": { "$oid": "550b2888e9dd90068070c31f" },
"index" : 0,
"status": "Unpublished"
},
{
"_id" : { "$oid" : "550b288be9dd90068070c320" },
"index" : 1,
"status" : "Unpublished"
}
]
}
]
}
以及我们只返回包含至少一个包含所有已发布幻灯片的已发布幻灯片的部分所需的结果
{
"_id" : { "$oid" : "550b2873e9dd90068070c31b" },
"dateCreated" : { "$date" : 1426794611867 },
"sections" : [
{
"_id" : { "$oid" : "550b2881e9dd90068070c31d" },
"index" : 0,
"name" : "Section 2",
"slides" : [
{
"_id" : { "$oid" : "55105b87e9dd90068033ba4a" },
"index" : 1,
"status" : "Published"
}
]
}
]
}
到目前为止,我有这个:
col.aggregate
([
{$match : {'name': name}},
{$unwind:'$sections'},
{$unwind:'$sections.slides'},
{$match:{'$sections.slides.status': "Published"}},
{$group:{_id:'$_id', slides:{$push:'$slides'}}}
])
我很难将头部缠绕在分组上,特别是将每个幻灯片数组嵌套在其父节数组中。另外,我想省略任何空白部分。
我之前从未使用过聚合方法,但我相信这是正确的方法。当涉及到深层嵌套的数组时,mongo文档有点稀疏。
答案 0 :(得分:2)
了解MongoDB管道的$redact阶段。 在第一次迭代我做了这个:
.aggregate({
$redact: {
$cond: {
if: { $eq: ["$status", "Unpublished"] },
then: "$$PRUNE",
else: "$$DESCEND"
}
}
}, {
$redact: {
$cond: {
if: { $eq: ["$slides", []] },
then: "$$PRUNE",
else: "$$DESCEND"
}
}
})
您可以尝试以更优雅的方式重写它。我非常确定有一种方法可以使用单个$ redact阶段,但是你必须浏览手册并找到合适的运算符。希望它会有所帮助。祝你好运。