本文介绍了如何在组内推送多列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来我的查询不会像我期望的那样

It seems my query will won't act as my expect

我想按 name 分组,并将location1和location2映射到名为 locations

I want to group by name and mapping location1 and location2 into an array called locations

{name: "Jack", localtion1: "Taiwan", localtion2: "France"},
{name: "Jack", localtion1: "Japan", localtion2: "Taiwan"},
{name: "Mary", localtion1: "China", localtion2: "Taiwan"}

预期结果

{
    name: "Jack",
    localtions: ["Taiwan", "France", "Japan"]
},
{name: "Mary", localtions: ["China", "Taiwan"]}

查询

db.collection.aggregate([
    {
        $group: {
            _id: "$name",
            "localtions":{
                $addToSet: "$localtion1"
            },
            "localtions":{
                $addToSet: "$localtion2"
            }
            count: { $sum: 1 }
        }
    },
    {
        $project: {
            name: "$_id",
            localtions: "$localtions",
            _id: 0
        }
    },
])

推荐答案

您可以使用 $ setUnion 运算符.对于其他 set操作符,请阅读 this .

You can use the $setUnion operator. For others set operators read this.

db.collection.aggregate([
        {
            "$group": {
                "_id": "$name",
                "localtion1": { "$addToSet": "$localtion1" },
                "localtion2": { "$addToSet": "$localtion2" }
             }
        },
        {
            "$project": {
                "name": "$_id",
                "localtions": { "$setUnion": [ "$localtion1", "$localtion2" ] },
                "_id": 0
            }
        }
])

输出

{ "name" : "Mary", "localtions" : [ "Taiwan", "China" ] }
{ "name" : "Jack", "localtions" : [ "France", "Japan", "Taiwan" ] }

这篇关于如何在组内推送多列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:39