douxu5845 2019-03-01 21:36
浏览 81
已采纳

mgo将mapreduce转换为聚合命令

I am trying to convert this function here from mapreduce to aggregation.

https://github.com/mendersoftware/deviceauth/blob/be2f9745e14bbe87121d99ac6c396f41ca7438e2/store/mongo/datastore_mongo.go#L826

The result from above function will be [{pending 1}].

When I run my match group I get [{pending 0}] from the following code below:

    mat := bson.M{
            "$match": bson.M{"device_id": devId},
    }

    grp := bson.M{
            "$group": bson.M{
                    "_id": "$status",
                    "count": bson.M{
                            "$sum": 1,
                    },
            },
    }

    pipe := c.Pipe([]bson.M{mat,grp})
    pipe.One(&result)

But the same I think command in mongo shell gives [{pending 1}].

db.getCollection("auth_sets").aggregate([
{
    $match: {
        device_id:"5c79601d152ece00012f5831"
    }
},
{
    $group: {
        _id:"$status",
        count: {
            $sum: 1
        }
     }
},
]);

How can I get it so my pipe will return [{pending 1}]?

I am changing it so I can use Mongo Atlas with does not allow mapreduce.

  • 写回答

1条回答 默认 最新

  • dongtangu6889 2019-03-02 07:07
    关注

    Your mgo query structure is OK, the problem is the name of the count field. The model expects Value:

    var result []struct {
        Status string `bson:"_id"`
        Value  int
    }
    

    So change the $group stage to this:

    grp := bson.M{
            "$group": bson.M{
                    "_id": "$status",
                    "value": bson.M{   // Note lowercased "value"!
                            "$sum": 1,
                    },
            },
    }
    

    And it should work. Or change the model if you can:

    var result []struct {
        Status string `bson:"_id"`
        Value  int    `bson:"count"`
    }
    

    Only one of them needs to be changed, to be aligned with the other.

    One last thing: If you use Query.One(), then the result must not be a slice (One() expects one document exactly).

    Use a slice type for result if you use e.g. Query.All().

    So if you're going to use Query.One(), use result:

    var result struct {
        Status string `bson:"_id"`
        Value  int    `bson:"count"`
    }
    

    Also Query.One() and Query.All() return an error, do check it!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题