When I try to query to collection using ObjectID, I got no documents.
objID, err := primitive.ObjectIDFromHex("6812a288d8169501c71c69b2")
if err != nil {
return domain.User{}, ErrFailToConvertID
}
filter := bson.M{"_id": objID}
res := r.collection.FindOne(ctx, filter)
if err := res.Err(); err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
err = ErrUserNotExists
}
return domain.User{}, err
}
var result domain.User
err = res.Decode(&result)
return result, err
I tried to query using mongo shell to query
db.users.find({ _id: ObjectId("6812a288d8169501c71c69b2") })
And it's still return document.
Image: https://i.ibb.co/xKF58WQP/Screenshot-2025-05-01-061736.png
Answer
I found an answer.
- Removal of the
bson/primitive
package. This package is now merged with thebson
package. To update your code, remove anybson/primitive
import statements and change any instance ofprimitive.ObjectID
tobson.ObjectId
.
Ref: https://www.mongodb.com/docs/drivers/go/upcoming/whats-new/#what-s-new-in-2.0