Home  >  Article  >  Backend Development  >  How to Retrieve a MongoDB Document by Its Object ID in Go?

How to Retrieve a MongoDB Document by Its Object ID in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 19:35:29687browse

How to Retrieve a MongoDB Document by Its Object ID in Go?

Finding a Document by Object ID in MongoDB with Go

You're attempting to retrieve a MongoDB document using its auto-generated _id field, but your current code fails to return a result. Let's dive into the issue and provide a solution.

In the provided code, you're creating a RawValue to represent the document ID:

var documentID bson.RawValue
documentID.Type = 7
documentID.Value = []byte("5c7452c7aeb4c97e0cdb75bf")

However, this approach is unnecessary. You can directly create an ObjectID using the primitive.ObjectIDFromHex function:

objID, _ := primitive.ObjectIDFromHex("5c7452c7aeb4c97e0cdb75bf")

With the correct ObjectID, you can then issue a FindOne operation on your collection:

value := collection.FindOne(ctx, bson.M{"_id": objID})

This code should now correctly retrieve the document you're seeking from the database.

The above is the detailed content of How to Retrieve a MongoDB Document by Its Object ID in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn