3 回答
TA贡献1895条经验 获得超3个赞
objID, _ := primitive.ObjectIDFromHex("5c7452c7aeb4c97e0cdb75bf")
value := collection.FindOne(ctx, bson.M{"_id": objID})
TA贡献1821条经验 获得超6个赞
你可以使用这样的东西:
var userDB user
objectIDS, _ := primitive.ObjectIDFromHex(userID)
collectionUser := dBClient.Database("MyDatabase").Collection("Users")
filter := bson.M{"_id": objectIDS}
err := collectionUser.FindOne(ctx, filter).Decode(&userDB)
if err != nil {
fmt.Println("errror retrieving user userid : " + userID)
}
TA贡献1785条经验 获得超4个赞
package main
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"context"
)
// get collection "users" from db() which returns *mongo.Client
var userCollection = db().Database("goTest").Collection("users")
func mongodriver_find_by_id() {
objectId, err1 := primitive.ObjectIDFromHex("6041c3a6cfcba2fb9c4a4fd2")
if err1 != nil {fmt.Println(err1)}
findone_result := userCollection.FindOne(context.TODO(), bson.M{"_id":objectId})
var bson_obj bson.M
if err2 := findone_result.Decode(&bson_obj); err2 != nil {fmt.Println(err2)}
fmt.Println("bson_obj:", bson_obj)
}
- 3 回答
- 0 关注
- 202 浏览
添加回答
举报