我嘗試從我的 Go 代碼中獲取 MongoDB 集合的最大值。我應該使用什么類型來解碼結果?當我使用bson.D{}asval2類型時,結果看起來像[{_id <nil>} {max 66} {cnt 14}].這是代碼: filter := []bson.M{{ "$group": bson.M{ "_id": nil, "max": bson.M{"$max": "$hellid"}, }}, } cursor, err := collection.Aggregate(ctx, filter) for cursor.Next(ctx) { val2 := ??? err := cursor.Decode(&val2) fmt.Printf("cursor: %v, value: %v\n", cursor.Current, val2) }}
1 回答

動漫人物
TA貢獻1815條經驗 獲得超10個贊
正如您所介紹的那樣,使用bson.D已經有效。問題可能是您無法“輕松”獲得max和cnt值。
使用如下結構對結果文檔進行建模:
type result struct {
Max int `bson:"max"`
Count int `bson:"cnt"
}
雖然cnt不是由您提供的示例代碼生成的。
進而:
var res result
err := cursor.Decode(&res)
- 1 回答
- 0 關注
- 123 瀏覽
添加回答
舉報
0/150
提交
取消