在 golang mongodb 中的集合列表中打印集合
Print collection in a list of a collection in mongodb in golang
要打印来自 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)
但是,我得到了一些十六进制值
Mongo 在 go 语言中 api 不同于 mongo。
找到 returns 游标不是集合。
您应该将代码更改为:
var items []Items
cur, err := likes_collection.Find(context.Background(), bson.D{{}})
if err != nil {
panic(err)
}
cur.All(context.Background(),&items)
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)
要打印来自 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)
但是,我得到了一些十六进制值
Mongo 在 go 语言中 api 不同于 mongo。
找到 returns 游标不是集合。
您应该将代码更改为:
var items []Items
cur, err := likes_collection.Find(context.Background(), bson.D{{}})
if err != nil {
panic(err)
}
cur.All(context.Background(),&items)
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)