问题
I have a MongoDB collection with 3 fields:
_id: ObjectId
field1: Number
field2: Number
I am doing this aggregation to get "distinct" field1/field2 rows and doing a total count of the results. This works OK in the client (Robo3t):
db.mycollection.aggregate([
{
$group: {
_id: { field1: "$field1", field2: "$field2" },
}
},
{
$group: {
_id: null, count: { $sum: 1 }
}
}
])
Result:
{
"_id" : null,
"count" : 57.0
}
How could I do this aggregation in Go using mongo-driver?
There is this method to perform aggregations but the documentation is not clear to me. I understand that I should do some kind of bson query but I don't know where to start.
回答1:
group :=[]bson.M{bson.M{
"$group": bson.M{
"_id":bson.M{
"field1": "$field1",
"field2": "$field2"
}
}
},
bson.M {
"$group": bson.M{
"_id":nil,
"count": bson.M{
"$sum":1
}
}
}
}
cursor, err := coll.Aggregate(context.Background(), mongo.Pipeline{group})
if err != nil {
log.Fatal(err)
}
Try the above solution, It will works.
回答2:
To complement the accepted solution I am sharing the full code with the cursor iteration and decode. I changed the "_id": nil
to "_id": ""
to receive strings and be able to decode to a struct without issues.
pipeline := []bson.M{
{
"$group": bson.M{"_id": bson.M{"field1": "$field1", "field2": "$field2"}},
},
{
"$group": bson.M{"_id": "", "count": bson.M{"$sum": 1}},
},
}
cursor, err := coll.Aggregate(ctx, pipeline)
if err != nil {
return err
}
type Result struct {
ID string `bson:"_id"`
Count int `bson:"count"`
}
var res Result
for cursor.Next(ctx) {
err := cursor.Decode(&res)
if err != nil {
return err
}
fmt.Printf("Element %v", res)
}
来源:https://stackoverflow.com/questions/59513341/how-to-perform-aggregations-in-go-using-mongo-driver