duanbi7204 2016-07-21 16:04
浏览 61

mgo中的Golang和MongoDB查询

So I have this mongo db query which works fine:

db.levels.aggregate([{
         $match: {
                  "_id": {$lt: ObjectId("56410480f91e505237902dae")}
         },
},     
        { $group: 
            {             
                 "_id": {"title": "Level 11"},
                 "totalAmount": { $sum: "$rewardCoins"}
            }
        } 
])

It should get all rows before give id and based on rewardCoins calculate sum.

Now with mgo in golang I'm strugling to get this working... I'm going with pipe but my resultset is empty.

pipe := c.Pipe([]bson.M{{"$match": bson.M{"_id": bson.M{"$lt": level.ID}},
        "$group": bson.M{"_id":"$title", "totalReward": bson.M{"$sum": "$rewardCoins"}}}})

    res :=[]bson.M{}

    pipe.All(&res)

What I'm doing wrong here ? Thanks.

UPDATE

Here is how my simple rows look like in db:

{ "_id" : ObjectId("5613f5ad153678d113d01f4a"), "title" : "Level 1", "rewardCoins" : NumberLong(1000) }
{ "_id" : ObjectId("56159796153678d113d02d60"), "title" : "Level 2", "rewardCoins" : NumberLong(50000) }
  • 写回答

2条回答 默认 最新

  • doubeijian2257 2016-07-21 16:52
    关注

    The structure in Go isn't the same as in the other language. If you hit Enter after every brace or comma, add commas where Go wants them, and run go fmt, you get one bson.M:

    pipe := c.Pipe(
        []bson.M{
            {
                "$match": bson.M{
                    "_id": bson.M{
                        "$lt": level.ID,
                    },
                },
                "$group": bson.M{
                    "_id": "$title",
                    "totalReward": bson.M{
                        "$sum": "$rewardCoins",
                    },
                },
            },
        },
    )
    

    Another way to see it is that there's no }, { before $group in the Go, whereas there is in the JSON-y version.

    Indenting this way seems like a good idea in general; the eyes can get lost in a sea of brackets otherwise.

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题