使用Golang进行Mongodb聚合操作

5
我将为您翻译以下内容,希望能对您有所帮助:

我有一个mongodb集合如下:

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

我希望找到基于评论数量的前五篇文档。我可以使用以下命令在命令提示符中找到所需的结果:
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

想知道我做错了什么,以及如何解决这个问题。

非常感谢任何帮助。

提前致谢。

Ripul


1
fmt.Printf("ERROR : %s\n", err) 更改为 fmt.Printf("ERROR : %s\n", err1.Error()) - DanG
你好,感谢您的回复。我已经按照您建议的方法更改了代码,但现在出现了这个输出:"ERROR : Unsupported document type for unmarshalling: []bson.M"。 - Ripul
你需要定义一个结构体,用于加载结果。然后使用json:"myName"字段名称标记该结构体以进行映射。请参考:http://golang.org/pkg/encoding/json/#Marshal - DanG
1个回答

6

更改

 err1 := pipe.One(&results)

to

err1 := pipe.All(&results)

太好了,我不确定为什么,但它解决了问题。我只是在想是否因为结果被声明为数组。无论如何,非常感谢。 - Ripul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接