如何在聚合mongodb的$project stage中重复所有字段键并设置新值?

x8diyxa7  于 2023-01-08  发布在  Go
关注(0)|答案(1)|浏览(147)

我有一个模式模型,有很多字段,如下例所示,我想将suggest_foo中的根字段克隆到聚合的$project阶段,而不必手动重写这些字段,然后将这些字段设置为新值作为我的逻辑。
示例:

  • 模式模型:
const fooSchema = new Schema({
   suggest_foo: 
     foo1: String,
     foo2: String,
     foo3: String,
     foo4: String,
     foo5: String,
   }
   ...
})
  • 种子数据:
{
   suggest_foo: {
     foo1: 'Foo1',
     foo2: 'Foo2',
     foo3: 'Foo3',
     foo4: 'Foo4',
     foo5: 'Foo5',
   }
}
  • 聚合查询代码:
fooSchema.aggregate([
   ...
   {
     $project: {
        // I want to clone root in suggest_foo (eg: foo1, foo2, foo(n)...) to be here.
     }
   }
])

我期望的输出结果如下所示:

{
     foo1: 'Foo1 maybe you like',
     foo2: 'Foo2 maybe you like',
     foo3: 'Foo3 maybe you like',
     foo4: 'Foo4 maybe you like',
     foo5: 'Foo5 maybe you like',
  }
3bygqnnd

3bygqnnd1#

一个选项是将$replaceRoot$arrayToObject$objectToArray一起使用,因为这将允许您在循环中操作数组:

db.collection.aggregate([
  {$replaceRoot: {
      newRoot: {
        $arrayToObject: {
          $map: {
            input: {$objectToArray: "$suggest_foo"},
            in: {
              v: {$concat: ["$$this.v", " maybe you like"]},
              k: "$$this.k"
            }
          }
        }
      }
  }}
])

了解它在playground example上的工作原理

相关问题