英文:
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数据库中存在。这里是查看的图片。
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.
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论