golang中的Mongodb聚合
发布时间:2020-12-16 09:24:39 所属栏目:大数据 来源:网络整理
导读:我有一个像这样的 mongodb集合: { source: "...",url: "...",comments: [ ..... ]} 我想根据评论的数量找到前5个文件.我可以在命令提示符中使用以下查询找到所需的结果: db.gmsNews.aggregate([ { $match:{source:"..."} },{ $unwind: "$comments" },{ $gr
我有一个像这样的
mongodb集合:
{ source: "...",url: "...",comments: [ ..... ] } 我想根据评论的数量找到前5个文件.我可以在命令提示符中使用以下查询找到所需的结果: db.gmsNews.aggregate([ { $match:{source:"..."} },{ $unwind: "$comments" },{ $group: { _id: "$url",size: { $sum: 1 },} },{ $sort : { size : -1 } },{ $limit : 5 } ]) 这给了我以下输出: { "_id" : "...","size" : 684 } { "_id" : "...","size" : 150 } 现在我想使用mgo驱动程序将此查询转换为golang.我通过以下方式使用管道: o1 := bson.M{ "$match" :bson.M {"source":"..."},} o2 := bson.M{ "$unwind": "$comments",} o3 := bson.M{ "$group": bson.M{ "_id": "$url","size": bson.M{ "$sum": 1,},} o4 := bson.M{ "sort": bson.M{ "size": -1,} o5 := bson.M{ "$limit": 5,} operations := []bson.M{o1,o2,o3,o4,o5} pipe := c.Pipe(operations) // Run the queries and capture the results results := []bson.M{} err1 := pipe.One(&results) if err1 != nil { fmt.Printf("ERROR : %sn",err1.Error()) return } fmt.Printf("URL : %s,Size: %sn",results[0]["_id"],results[0]["size"]) 不幸的是,这不起作用,我得到以下输出: ERROR : Unsupported document type for unmarshalling: []bson.M 只是想知道我做错了什么以及如何解决这个问题. 任何帮助将受到高度赞赏. 提前致谢. Ripul 解决方法
更改
err1 := pipe.One(&results) 至 err1 := pipe.All(&results) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |