如何使用MongoDB聚合框架嵌套嵌套数组并删除空数组?

时间:2016-12-12 03:45:15

标签: mongodb aggregation-framework

我试图转换我的文档,如下所示。我已尝试使用$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: [

  ]
}

1 个答案:

答案 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"}
      }
    }
  ]    
);