Mongodb 获取子数组的不同值作为附加属性

Mongodb 获取子数组的不同值作为附加属性,mongodb,mongodb-query,nosql,Mongodb,Mongodb Query,Nosql,例如,我们有一个包含以下文档的集合: { "_id" : "1", "Category" : "11", "Type" : 1, "Active" : true, "IsValid" : null, . . . . "AllTags": ["

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

{
    "_id" : "1",
    "Category" : "11",
    "Type" : 1,
    "Active" : true,
    "IsValid" : null,
     .
     .
     .
     .
    "AllTags": ["Product", "Product", "Product", "Response", "Comment", "Response"]
}
{
    "_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
}
我们如何输出与这些文档完全相同的文档,但这些文档将包含带有不同标签的附加字段:
[“产品”、“响应”、“注释”]
。因此,生成的文档将如下所示:

{
    "_id" : "1",
    "Category" : "11",
    "Type" : 1,
    "Active" : true,
    "IsValid" : null,
     .
     .
     .
     .
    "AllTags": ["Product", "Product", "Product", "Response", "Comment", "Response"]
}
{
    "_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
}
我正在尝试添加stage$AddFields

{ "$addFields" : { "Tags" : {"$reduce": { "input": "$AllTags", initialValue: [], in: {  
        $cond: { if: { "$$this": {$nin: ["$$value"]} } , then:  { $concatArrays : ["$$value", ["$$this"]] }, else: ?  }            
    } } } } }
但它给出了这个错误:
“无效的$addFields::由::无法识别的表达式“$$this”
,我不知道在
$cond
op的
中放置什么。

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

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

omg,在文档中多次看到该运算符,但始终认为“set”是动词,而不是“名词”。感谢您的快速回复。该操作员有很多好处,但文档中没有提到。您从哪里获得这些信息?在网上有没有比官方网站更先进的知识来源?我从别人的答案中学到了。这也是一个很好的知识来源,很多有经验的人都在这里。