首页 > 解决方案 > 获取子数组的不同值作为附加属性

问题描述

例如,我们有一个包含如下文档的集合:

{
    "_id" : "1",
    "Category" : "11",
    "Type" : 1,
    "Active" : true,
    "IsValid" : null,
     .
     .
     .
     .
    "AllTags": ["Product", "Product", "Product", "Response", "Comment", "Response"]
}

我们如何输出与这些完全相同的文档,但其中将包含具有不同标签的附加字段:["Product", "Response", "Comment"]。因此生成的文档将如下所示:

{
    "_id" : "1",
    "Category" : "11",
    "Type" : 1,
    "Active" : true,
    "IsValid" : null,
     .
     .
     .
     .
    "AllTags": ["Product", "Product", "Product", "Response", "Comment", "Response"],
    "Tags": ["Product", "Response", "Comment"] //property calculated from AllTags
}

我正在尝试添加阶段 $AddFields

{ "$addFields" : { "Tags" : {"$reduce": { "input": "$AllTags", initialValue: [], in: {  
        $cond: { if: { "$$this": {$nin: ["$$value"]} } , then:  { $concatArrays : ["$$value", ["$$this"]] }, else: ?  }            
    } } } } }

但它给出了这个错误:"Invalid $addFields :: caused by :: Unrecognized expression '$$this'",而且我不知道在elseop $cond.

标签: mongodbmongodb-querynosql

解决方案


您可以使用$setUnion运算符,过滤掉其结果中的重复项以输出仅包含唯一条目的数组,

db.collection.aggregate([
  {
    $addFields: {
      Tags: { $setUnion: "$AllTags" }
    }
  }
])

操场


推荐阅读