如何将嵌套键展平到 Mongoose 中的顶级对象中

How to flatted nested keys into the top level object in Mongoose

我有这样的文件:

[
  {
    title: 'apple',
    attributes: {
      colour: 'red',
      kind: 'fruit'
  },
  {
    title: 'broccoli',
    attributes: {
      colour: 'green',
      kind: 'vegetable'
    }
  },
]

在我的聚合管道中,我想基本上将层次结构展平一层,使其看起来像这样:

[
  {
    title: 'apple',
    colour: 'red',
    kind: 'fruit'
  },
  {
    title: 'broccoli',
    colour: 'green',
    kind: 'vegetable'
  }
]

事实是,嵌套对象中的键在文档中是动态的,因此我无法 $project 静态地设置它们。我需要将这些嵌套的 key/value 对动态拉到顶部对象。

使用聚合框架可能是这样的:

db.collection.aggregate([
{
 $replaceRoot: {
  newRoot: {
    $mergeObjects: [
      "$$ROOT",
      "$attributes"
    ]
   }
  }
 },
 {
 $project: {
   attributes: 0
   }
 }
])

解释:

  1. 用根对象和属性之间的合并对象替换根
  2. 从输出中删除属性对象。

playground