如何使用golang在mongodb中找到数据?

在此代码中,我试图根据.但是每当我运行此代码时,它都会给我一个错误.userIDmongo: no documents in result

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

http://img2.mukewang.com/630e18f000018e0f13640765.jpg

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)


芜湖不芜
浏览 93回答 1
1回答

呼如林

您正在搜索字符串,但却是一个 ._id_idObjectIdobjectId, err:=primitive.ObjectIDFromHex(userID)collection.FindOne(context.TODO(), bson.M{"_id": objectId}).Decode(&result)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go