我试图转换我的文档,如下所示。我已尝试使用$unwind
运算符,然后$group
运算符与$push
运算符组合以重新构建$user_mentions
数组,但这也推动了所有空阵列,我又回到原点。
我的开始:
{
_id: "6222407",
name: "Chris",
user_mentions: [
[],
[{_id:"963222", name: "Bob"}, {_id:"234324", name: "Fred"}]
]
},
{
_id: "34566",
name: "Tim",
user_mentions: [
[]
]
},
{
_id: "65343",
name: "Sean",
user_mentions: [
[],
[]
]
}
}
我想要的是什么:
{
_id: "6222407",
name: "Chris",
user_mentions: [
{_id:"963222", name: "Bob"},
{_id:"234324", name: "Fred"}]
]
},
{
_id: "34566",
name: "Tim",
user_mentions: [
]
},
{
_id: "65343",
name: "Sean",
user_mentions: [
]
}
答案 0 :(得分:2)
由于文档布局的性质,您必须展开两次(数组中的数组)。还可以在第二次展开时使用preserveNullAndEmptyArrays将空数组保留在文档中。
这是聚合:
db.collection.aggregate(
[
{
$unwind: "$user_mentions"
},
{
$unwind: { path: "$user_mentions", preserveNullAndEmptyArrays: true }
},
{
$group: {
_id : "$_id",
name : {$first : "$name"},
user_mentions : { $push : "$user_mentions"}
}
}
]
);