How to find by id in golang and mongodb

It should be _id not Id:

c.FindId(bson.M{"_id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")})

Some sample code that i use.

func (model *SomeModel) FindId(id string) error {
    db, ctx, client := Drivers.MongoCollection("collection")
    defer client.Disconnect(ctx)

    objID, err := primitive.ObjectIDFromHex(id)

    if err != nil {
        return err
    }

    filter := bson.M{"_id": bson.M{"$eq": objID}}


    if err := db.FindOne(ctx, filter).Decode(&model); err != nil {
        //fmt.Println(err)
        return err
    }

    fmt.Println(model)
    return nil
}

Use can do the same with Golang official driver as follows:

// convert id string to ObjectId
objectId, err := primitive.ObjectIDFromHex("5b9223c86486b341ea76910c")
if err != nil{
    log.Println("Invalid id")
}

// find
result:= client.Database(database).Collection("user").FindOne(context.Background(), bson.M{"_id": objectId})
user := model.User{}
result.Decode(user)

Tags:

Crud

Mongodb

Go