I am trying fetch documents from mongdb using golang code base. I created a pipeline and am using aggregate function like this:
pipeline := []bson.M{
bson.M{
"$group": bson.M{"_id": "$user_id", "score": bson.M{"$max": "$score"}},
},
bson.M{
"$sort": bson.M{"score": 1},
},
bson.M{
"$limit": 10,
},
}
collection := dBClient.Database("db").Collection("collection")
iter, err := collection.Aggregate(context.Background(), pipeline)
var sc score
for iter.Next(context.Background()) {
iter.Decode(&sc)
if err != nil {
log.Fatal(err)
}
//print element data from collection
fmt.Printf("Element %v", sc)
}
type score struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
UserID string `bson:"user_id"`
Score int32 `bson:"score"`
Timestamp int64 `bson:"timestamp"`
}
but all i am getting is bunch of zeros
Element {ObjectID("000000000000000000000000") 0 0}
Element {ObjectID("000000000000000000000000") 0 0}
Element {ObjectID("000000000000000000000000") 0 0}
Element {ObjectID("000000000000000000000000") 0 0}
Element {ObjectID("000000000000000000000000") 0 0}
Element {ObjectID("000000000000000000000000") 0 0}
Element {ObjectID("000000000000000000000000") 0 0}
Element {ObjectID("000000000000000000000000") 0 0}
Element {ObjectID("000000000000000000000000") 0 0}
same query runs fine on robo3t
db.getCollection('collection').aggregate([
{"$group":
{_id:"$user_id",
score:{"$max":"$score"}}},
{"$sort":{"score":-1}},
{"$limit":10}
])
although when i don't use '$group' it works fine and gives me proper records.
pipeline := []bson.M{
bson.M{
"$sort": bson.M{"score": 1},
},
bson.M{
"$limit": 10,
},
}
what am i missing?
i am using go.mongodb.org/mongo-driver/mongo driver