如何使用Golang在MongoDB中查找数据?

huangapple go评论108阅读模式
英文:

How to find the data in mongodb using golang?

问题

在这段代码中,我试图根据userID从MongoDB中查找数据。但是每当我运行这段代码时,它都会给我一个错误,提示mongo: no documents in result

我在mongo shell中写了db.dataStored.findOne({_id: ObjectId("60a60718503219dfd740f9fe")}),但是它给我返回了一个null结果。尽管数据在MongoDB数据库中存在。这里是查看的图片。

如何使用Golang在MongoDB中查找数据?

userID := "60a60718503219dfd740f9fe"
var result Trainer

collection := client.Database("PMS").Collection("dataStored")
err = collection.FindOne(context.TODO(), bson.M{"_id": userID}).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)

英文:

In this code, I am trying to find the data from MongoDB based on the userID. But whenever I run this code, it gives me an error that mongo: no documents in result.

I wrote db.dataStored.findOne({_id: ObjectId("60a60718503219dfd740f9fe")}) in mongo shell also but it gave me a null result. Although the data is present in the MongoDB database. Here is the picture to see.

如何使用Golang在MongoDB中查找数据?

userID := "60a60718503219dfd740f9fe"
var result Trainer

collection := client.Database("PMS").Collection("dataStored")
err = collection.FindOne(context.TODO(), bson.M{"_id": userID}).Decode(&result)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)

答案1

得分: 1

你正在搜索一个字符串 _id,但是 _id 是一个 ObjectId

objectId, err := primitive.ObjectIDFromHex(userID)
collection.FindOne(context.TODO(), bson.M{"_id": objectId}).Decode(&result)
英文:

You are searching for a string _id, but _id is an ObjectId.

objectId, err:=primitive.ObjectIDFromHex(userID)
collection.FindOne(context.TODO(), bson.M{"_id": objectId}).Decode(&result)

huangapple
  • 本文由 发表于 2021年5月20日 23:28:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/67623476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定