Home > Backend Development > Golang > 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
Release: 2024-10-31 19:35:29
Original
779 people have browsed it

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")
Copy after login

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

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

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template