首页 > 解决方案 > Mongodb $mergeObjects 使用变量属性作为对象键

问题描述

我目前正在编写一个聚合并有一个名为tags复杂对象的数组,例如:{name: 'tag1'}

我想确保数组只包含 unique tags

    {
        $addFields: {
            uniqueTags: {
                $reduce: {
                    input: "$tags",
                    initialValue: {},
                    in: {$mergeObjects: {"$$this.name": "$$this"}}
        }}
    }},

上面的代码失败,因为我使用$$this.name对象键。例如,如果我将其更改为其他内容,5则聚合工作将变得完美。

标签: mongodbmongoosemongoid

解决方案


$addToSet works for nested objects.


推荐阅读