golang的Mongodb聚合

golang的Mongodb聚合,mongodb,go,Mongodb,Go,我有这样一个mongodb系列: { source: "...", url: "...", comments: [ ..... ] } 我想根据评论的数量找到前5个文档。我可以使用命令提示符中的以下查询找到所需的结果: db.gmsNews.aggregate([ { $match:{source:"..."} }, { $unwind: "$comments" }, { $group: {

我有这样一个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 : %s\n", err1.Error())
    return
}

fmt.Printf("URL : %s, Size: %sn", results[0]["_id"], results[0]["size"])
不幸的是,这不起作用,我得到以下输出:

ERROR : Unsupported document type for unmarshalling: []bson.M
只是想知道我做错了什么,以及如何解决这个问题

我们将非常感谢您的帮助

提前谢谢

里普尔

变化

 err1 := pipe.One(&results)


fmt.Printf(“错误:%s\n”,err)
更改为
fmt.Printf(“错误:%s\n,err1.ERROR())
Hi,感谢您的回复。我已经用您建议的方法更改了代码,现在得到了以下输出:“错误:不支持解组的文档类型:[]bson.M”。您需要定义一个结果将加载到的结构。然后用
json:“myName”
字段名标记该结构,以将其映射。看:很好,我不知道为什么,但它解决了问题。我只是想知道这是否是因为结果被声明为数组。无论如何,非常感谢你。
err1 := pipe.All(&results)