How to Find a Document by _id in MongoDB using Go?

DDD
Release: 2024-10-30 15:28:03
Original
815 people have browsed it

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template