所有字段上的 Concat 数组 MongoDB

aja*_*228 5 mongodb aggregation-framework

想象一下我有这个集合:

{
  id: 1,
  b: { 
   "field1": ['foo'],
   "field2": ['bar']
  }
}
{
  id: 2,
  b: { 
   "field2": ["foobar"],
   "field3": ["foofoo"]
  }
}
Run Code Online (Sandbox Code Playgroud)

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

{
 id: 1,
 b_grouped: ['foo', 'bar']
}
{
 id: 2,
 b_grouped: ["foobar", "foofoo"]
}
Run Code Online (Sandbox Code Playgroud)

我不知道文档中字段的所有名称,任何人都会知道如何执行这样的操作:

db.collection.aggregate(
   [
      { "$project": { "b_grouped": { $concatArrays: ["$b.*"] } } }
   ]
)
Run Code Online (Sandbox Code Playgroud)

tur*_*hal 9

你可以试试,

  • b使用$objectToArray从对象转换为数组后,将$reduce输入作为数组,这将转换对象为“k”(键)、“v”(值)格式的对象数组,
  • $ concatArrays到的concat initialValue ($$值)$raduce和的阵列b对象的字段$$ this.v
db.collection.aggregate([
  {
    $project: {
      b_grouped: {
        $reduce: {
          input: { $objectToArray: "$b" },
          initialValue: [],
          in: {
            $concatArrays: ["$$this.v", "$$value"]
          }
        }
      }
    }
  }
])
Run Code Online (Sandbox Code Playgroud)

操场