简体   繁体   中英

mongo-go-driver find a document by _id

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 = []byte("5c7452c7aeb4c97e0cdb75bf")
objID := documentID.ObjectID()
value := collection.FindOne(ctx, bson.M{"_id": objID})

The value I provided is a real document id I got from Mongo Express

"_id": ObjectID("5c7452c7aeb4c97e0cdb75bf")

In case you're wondering why I bother with RawValue, I found examples using bson.EC.ObjectID but bson package doesn't seem to have EC type, also I found some examples mentioning github.com/mongodb/mongo-go-driver/bson/objectid package, but I could not find that package either. I previously developed with mgo but I'm new to mongo-go-driver, so if you can point an easy way to declare an ObjectID.

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})

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)
}
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)


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM