Home > Article > Backend Development > How to Find a Document by _id in MongoDB using Go?
Finding a Document by _id in MongoDB using Go
To find a document by its auto-generated _id field using the mongo-go-driver, instantiate an ObjectID and use it as the value for the "_id" field in the query filter.
In the provided code, the bson.RawValue is used, but it's not necessary. Instead, use primitive.ObjectIDFromHex("") to convert the hexadecimal representation of the _id directly.
Updated Code:
<code class="go">import ( "context" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/primitive" ) func main() { ctx := context.Background() // Create a client client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://<host>:<port>")) if err != nil { // handle error } defer client.Disconnect(ctx) // Get a collection collection := client.Database("database").Collection("collection") // Parse the ObjectID from hexadecimal string id, err := primitive.ObjectIDFromHex("5c7452c7aeb4c97e0cdb75bf") if err != nil { // handle error } // Find the document by _id result := collection.FindOne(ctx, bson.M{"_id": id}) }</code>
The above is the detailed content of How to Find a Document by _id in MongoDB using Go?. For more information, please follow other related articles on the PHP Chinese website!