mongo-go-driver find a document by _id

前端 未结 2 1198
礼貌的吻别
礼貌的吻别 2021-01-05 09:29

I\'m trying to find a document by its auto generated _id field. Code below returns nothing:

var documentID bson.RawValue
documentID.Type = 7
documentID.Value         


        
相关标签:
2条回答
  • 2021-01-05 09:44

    You can use some thing like this:

    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)
    }
    
    0 讨论(0)
  • 2021-01-05 09:55

    As @Carlos mentioned, I changed my code as this and everything works well.

    objID, _ := primitive.ObjectIDFromHex("5c7452c7aeb4c97e0cdb75bf")
    value := collection.FindOne(ctx, bson.M{"_id": objID})
    
    0 讨论(0)
提交回复
热议问题