在MongoDB上对所有字段连接数组

5

想象我有这个集合:

{
  id: 1,
  b: { 
   "field1": ['foo'],
   "field2": ['bar']
  }
}
{
  id: 2,
  b: { 
   "field2": ["foobar"],
   "field3": ["foofoo"]
  }
}

我想使用MongoDB获取一个新的集合:

{
 id: 1,
 b_grouped: ['foo', 'bar']
}
{
 id: 2,
 b_grouped: ["foobar", "foofoo"]
}

我不知道文档中所有字段的名称,有没有人有办法执行这样的操作:
db.collection.aggregate(
   [
      { "$project": { "b_grouped": { $concatArrays: ["$b.*"] } } }
   ]
)

1
您的样本数据不是有效的JSON格式。这是两个文档还是一个? - Wernfried Domscheit
我在写这个时有些困惑,但我已经修复了它,实际上这是两个文档。 - aja228
1个回答

10
您可以尝试使用$reduce将输入的b转换为数组,方法是先使用$objectToArray将对象转换为数组,这将把以“k”(键),“v”(值)格式存储的对象转换为对象数组;再使用$concatArrays$reduceinitialValue ($$value)b对象的字段$$this.v所组成的数组相连。
db.collection.aggregate([
  {
    $project: {
      b_grouped: {
        $reduce: {
          input: { $objectToArray: "$b" },
          initialValue: [],
          in: {
            $concatArrays: ["$$this.v", "$$value"]
          }
        }
      }
    }
  }
])

Playground


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接