duanmanpi9358 2014-09-26 15:04
浏览 178
已采纳

Golang中的Mongodb聚合

I have a mongodb collection like this:

{
    source: "...",
    url:  "...",
    comments: [
        .....
    ]
}

I would like to find the top 5 documents based on the number of comments. I can find the desired result using the following query in the command prompt:

db.gmsNews.aggregate([
  {
     $match:{source:"..."}
  },
  {
     $unwind: "$comments"
  },
  {
     $group: {
        _id: "$url",
        size: {
           $sum: 1
        },
     }
  },
  {
     $sort : { size : -1 } 
  },
  { 
     $limit : 5
  }
])

This gives me the following output:

{ "_id" : "...", "size" : 684 }
{ "_id" : "...", "size" : 150 }

Now I would like to translate this query into golang using the mgo driver. I am using the pipe for this in the following way:

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 : %s
", err1.Error())
    return
}

fmt.Printf("URL : %s, Size: %sn", results[0]["_id"], results[0]["size"])

Unfortunately this is not working and I am getting the following output:

ERROR : Unsupported document type for unmarshalling: []bson.M

Just wondering what I'm doing wrong and how to resolve this.

Any help will be highly appreciated.

Thanks in advance.

Ripul

  • 写回答

1条回答 默认 最新

  • dongsha2792 2014-09-26 21:58
    关注

    Change

     err1 := pipe.One(&results)
    

    to

    err1 := pipe.All(&results)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)