duan1979768678
duan1979768678
2014-10-19 23:04

Mongodb中Golang mgo中的聚合

已采纳

Anybody knows what’s the equivalent of aggregate command we use in mongodb shell for golang mgo/bson?

Something like that:

aggregate([{$match:{my_id:ObjectId("543d171c5b2c1242fe0019")}},{$sort:{my_id:1, dateInfo:1, name:1}},{$group:{_id:"$my_id", lastEntry:{$max: "$dateInfo"},nm:{$last:"$name"}}}])
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongyi8795 dongyi8795 7年前

    Assuming that c is your Collection:

    pipe := c.Pipe([]bson.M{{"$match": bson.M{"name":"John"}}})
    resp := []bson.M{}
    err := pipe.All(&resp)
    if err != nil {
      //handle error
    }
    fmt.Println(resp) // simple print proving it's working
    

    GoDoc references:

    点赞 评论 复制链接分享
  • doujingao6210 doujingao6210 2年前

    Sample Code:

    pipe := c.Pipe([]bson.M{bson.M{"$match": bson.M{"type": "stamp"}},
            bson.M{"$group": bson.M{"_id": "$userid",
                "count": bson.M{"$sum": "$noofsr"}}}})
    
    resp := []bson.M{}
    iter := pipe.Iter()
    err = iter.All(&resp)
    

    Note:

    Please note that the line should end with (,) if you are not breaking in (,) it will throw error message even if your query is correct.

    Output:

    {
        "transactions": [
            {
                "_id": "three@four.com",
                "count": 10
            },
            {
                "_id": "one@two.com",
                "count": 12
            }
        ]
    }
    
    点赞 评论 复制链接分享

相关推荐