我正在尝试使用golang代码库从mongdb获取文档。 我创建了一个管道,并且正在使用如下聚合函数:
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"`
}
但是我得到的只是一堆零
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}
相同的查询在robo3t上运行正常
db.getCollection('collection').aggregate([
{"$group":
{_id:"$user_id",
score:{"$max":"$score"}}},
{"$sort":{"score":-1}},
{"$limit":10}
])
尽管当我不使用'$ group'时,它仍然可以正常工作并提供适当的记录。
pipeline := []bson.M{
bson.M{
"$sort": bson.M{"score": 1},
},
bson.M{
"$limit": 10,
},
}
我想念什么?
我正在使用go.mongodb.org/mongo-driver/mongo驱动程序