要從 mongodb 列印集合,以下是我在 python 中的代碼:
print(list(MongoClient(***).get_database("ChatDB").get_collection("room_members".find({'_id.username': username})))
我正在學習 Go,我正在嘗試將上述代碼翻譯成 golang。
我的代碼如下:
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("*****"))
if err != nil {
panic(err)
}
likes_collection := client.Database("ChatDB").Collection("likes")
cur, err := likes_collection.Find(context.Background(), bson.D{{}})
if err != nil {
panic(err)
}
defer cur.Close(context.Background())
fmt.Println(cur)
但是,我得到了一些十六進制值
uj5u.com熱心網友回復:
Go lang 中的 Mongo 與 mongo 不同的 api。
Find 回傳游標而不是集合。
您應該將代碼更改為:
var items []Items
cur, err := likes_collection.Find(context.Background(), bson.D{{}})
if err != nil {
panic(err)
}
cur.All(context.Background(),&items)
uj5u.com熱心網友回復:
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, options.Client().ApplyURI("***"))
if err != nil {
panic(err)
}
var likes []bson.M
likes_collection := client.Database("ChatDB").Collection("likes")
defer client.Disconnect(ctx)
cursor, err := likes_collection.Find(context.Background(), bson.D{{}})
if err != nil {
panic(err)
}
if err = cursor.All(ctx, &likes); err != nil {
panic(err)
}
fmt.Println(likes)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459367.html
下一篇:貓鼬在選擇中添加條件
