8
votes

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.

3
First of all, welcome to StackOverflow. Try this. I guess is the package you are looking for.Carlos Cavero
Thanks @CarlosCavero, simply defining the objID as primitive.ObjectID solved both problems.Serdar Kalaycı
@Serdar Kalayci you could add the working code as answer and mark it as accepted instead of editing it in the question. That way people with a similar problem will directly see, that this is solvedTobias Theel

3 Answers

24
votes

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

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


}