How to Get an Aggregate from a MongoDB Collection

我怕爱的太早我们不能终老 提交于 2019-12-08 05:28:29

Using Distinct()

What you want is easiest done using collection.distinct(). In MongoDB console it would look like this:

db.candles.distinct("symbol")

And in Go, using mgo, Query.Distinct():

var sess *mgo.Session = ... // Acquire session
c := sess.DB("dbname").C("candles")

var symbols []string
err := c.Find(nil).Distinct("symbol", &symbols)
if err != nil {
    log.Printf("Error: %v", err)
    return
}
fmt.Println(symbols)

Using the Aggregation Framework

You can also do it using MongoDB aggregation, which is available via the Collection.Pipe() method. You have to pass a slice to it, each element corresponds to an aggregation stage.

The result of an aggregation is always a list of documents, so if you want the result as a slice of strings, you have to do the "conversion" manually.

var sess *mgo.Session = ... // Acquire session
c := sess.DB("dbname").C("candles")

pipe := c.Pipe([]bson.M{
    {
        "$group": bson.M{
            "_id": "$symbol",
        },
    },
})
var results = []bson.M{}
if err := pipe.All(&results); err != nil {
    log.Printf("Error: %v", err)
    return
}

// results holds {"_id": "symbol"} documents
// To get a slice of symbols:
symbols := make([]string, len(results))
for i, doc := range results {
    symbols[i] = doc["_id"].(string)
}
fmt.Println(symbols)

For more techniques how to get a slice of values result instead of documents, see Is there a way to get slice as result of Find()?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!