如何在golang中进行Mongodb聚合

时间:2017-11-15 05:27:09

标签: mongodb go pipe aggregate mgo

我有一个像这样的MongoDB集合:

{ "_id" : ObjectId("5a017ee061313781045889ea"),  "device_id" : "1232213",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:37:37.006Z") }
{ "_id" : ObjectId("5a017f7b61313781045889eb"),  "device_id" : "1111",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:40:11.204Z") }
{ "_id" : ObjectId("5a017fdd61313781045889ec"),  "device_id" : "12222",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:41:49.452Z") }
{ "_id" : ObjectId("5a017ff561313781045889ed"),  "device_id" : "1232213",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:42:13.658Z") }

我想通过"device_id"区分它并按"pubtime"排序。

我知道Golang可以使用烟斗来做到这一点。但我不知道该怎么做。我尝试了什么:

o1 := bson.M{"_id": bson.M{"device_id": "$device_id"}}

o2 := bson.M{"pubtime": bson.M{"$last": "$pubtime"}}
o3 := bson.M{"$group": []bson.M{o1, o2}}
pipe := c.Pipe([]bson.M{o3})
var result = []bson.M{}
_ = pipe.All(&result)
fmt.Println(result)

结果是空的。

MongoDB没关系:

db.collections.aggregate({"$group":
                        {"_id":{"device_id":"$device_id"},
                        "pubtime":{"$last": "$pubtime"} ,
                       "value":{"$last": "$value"} ,
                        }});

2 个答案:

答案 0 :(得分:1)

你没有检查错误,这是你的主要问题。 Pipe.All()会返回您优雅丢弃的错误。不要那样做。

var result = []bson.M{}
err := pipe.All(&result)
fmt.Println(result, err)

这将打印:

[] a group's fields must be specified in an object

错误说明了一切。 $group的值必须为例如一个bson.M值,而不是bson.M的片段:

o3 := bson.M{"$group": bson.M{
    "_id":     bson.M{"device_id": "$device_id"},
    "pubtime": bson.M{"$last": "$pubtime"},
}}
pipe := c.Pipe([]bson.M{o3})
var result = []bson.M{}
err := pipe.All(&result)
fmt.Println(result, err)

现在输出将是:

[map[_id:map[device_id:12222] pubtime:2017-11-07 10:41:49.452 +0100 CET] map[_id:map[device_id:1111] pubtime:2017-11-07 10:40:11.204 +0100 CET] map[_id:map[device_id:1232213] pubtime:2017-11-07 10:42:13.658 +0100 CET]] <nil>

所以它有效。

要按pubtime排序结果,请使用$sort。这是最终的代码:

pipe := c.Pipe([]bson.M{
    {
        "$group": bson.M{
            "_id":     bson.M{"device_id": "$device_id"},
            "pubtime": bson.M{"$last": "$pubtime"},
        },
    },
    {"$sort": bson.M{"pubtime": 1}},
})
var result = []bson.M{}
err := pipe.All(&result)
fmt.Println(result, err)

如果您希望结果按降序排序,请使用:

{"$sort": bson.M{"pubtime": -1}}

另请注意,分组时,如果组_id是单个字段,则无需将其包装到对象中,只需使用$device_id作为组ID:

"$group": bson.M{
    "_id":     "$device_id",
    "pubtime": bson.M{"$last": "$pubtime"},
},

答案 1 :(得分:0)

可以在mongodb聚合管道中使用$group$first来完成

Mongodb shell查询

db.collection.aggregate([
    {$group: {_id:{device_id:"$device_id"}, pubtime:{$first:"$pubtime"}}}
]);

在mongo shell

中执行上述查询后得到的结果
{ "_id" : { "device_id" : "12222" }, "pubtime" : ISODate("2017-11-07T09:41:49.452Z") }
{ "_id" : { "device_id" : "1111" }, "pubtime" : ISODate("2017-11-07T09:40:11.204Z") }
{ "_id" : { "device_id" : "1232213" }, "pubtime" : ISODate("2017-11-07T09:37:37.006Z") }
相关问题