Mongodb 在子文档中创建多个数组的唯一列表。

Mongodb 在子文档中创建多个数组的唯一列表。,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我想在子文档中创建数组值的唯一列表 文件: { "_id" : ObjectId("5aee0e3c059638093b69c8b3"), "firstname" : "John", "lastname" : "Doe", "websites" : [ { "_id" : ObjectId("123"), "key" : "website2", "url" : "www.

我想在子文档中创建数组值的唯一列表

文件:

  {
    "_id" : ObjectId("5aee0e3c059638093b69c8b3"),
    "firstname" : "John",
    "lastname" : "Doe",
    "websites" : [ 
        {
            "_id" : ObjectId("123"),
            "key" : "website2",
            "url" : "www.xxx.com",
            "tags" : [ 
                "php", 
                "python", 
                "java"
            ]
        },
        {
            "_id" : ObjectId("456"),
            "key" : "website2",
            "url" : "www.yyy.com",
            "tags" : [ 
                "java",
                "php"
            ]
        },
        {
            "_id" : ObjectId("789"),
            "key" : "website3",
            "url" : "www.zzz.com",
            "tags" : [ 
                "java",
                "html",
                "css"
            ]
        }
    ]
}
预期产出:

{
    "_id" : ObjectId("5aee0e3c059638093b69c8b3"),
    "firstname" : "John",
    "lastname" : "Doe",
    "unique_tags": [
        "java",
        "php",
        "python",
        "html",
        "css",
    ],
    "websites" : [ 
        {
            "_id" : ObjectId("123"),
            "key" : "website2",
            "url" : "www.xxx.com",
            "tags" : [ 
                "php", 
                "python", 
                "java"
            ]
        },
        {
            "_id" : ObjectId("456"),
            "key" : "website2",
            "url" : "www.yyy.com",
            "tags" : [ 
                "java",
                "php"
            ]
        },
        {
            "_id" : ObjectId("789"),
            "key" : "website3",
            "url" : "www.zzz.com",
            "tags" : [ 
                "java",
                "html",
                "css"
            ]
        }
    ]
}
看起来Mongo具有独特的功能,但这在聚合查询中不起作用?!。 还尝试在websites.tags上展开并使用addToSet功能,但也没有正确的输出


有什么想法吗?

您可以尝试以下方法:

db.col.aggregate([
    {
        $addFields: {
            unique_tags: {
                $reduce: {
                    input: { 
                        $concatArrays: {
                            $map: {
                                input: "$websites",
                                as: "website",
                                in: "$$website.tags"
                            }
                        } 
                    },
                    initialValue: [],
                    in: { $setUnion : ["$$value", "$$this"]}
                }
            }
        }
    }
])
要展平阵列,请单击网站->可与一起使用的标记。然后,您将从所有网站获得一个包含所有标记的数组。若要仅获取唯一值,可以使用该值删除重复项