Skip to content

Instantly share code, notes, and snippets.

@niharrathod
Created October 1, 2022 11:45
Show Gist options
  • Select an option

  • Save niharrathod/e0f984270e03517f2215b7be89230356 to your computer and use it in GitHub Desktop.

Select an option

Save niharrathod/e0f984270e03517f2215b7be89230356 to your computer and use it in GitHub Desktop.

Revisions

  1. niharrathod created this gist Oct 1, 2022.
    131 changes: 131 additions & 0 deletions mongo-client.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,131 @@
    package main

    /*
    go get go.mongodb.org/mongo-driver@v1.10.1
    */

    import (
    "context"
    "fmt"
    "log"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readconcern"
    "go.mongodb.org/mongo-driver/mongo/readpref"
    "go.mongodb.org/mongo-driver/mongo/writeconcern"
    )

    const ID = "_id"

    type User struct {
    ID primitive.ObjectID `bson:"_id"`
    Name string `bson:"name"`
    EmailId string `bson:"emailId"`
    MobileNo string `bson:"mobileNo"`
    }

    var client *mongo.Client
    var userCollection *mongo.Collection

    func mongoClientInitialize() {
    mongoUrl := "mongodb://localhost:27017"
    database := "testdb"
    collection := "user"

    options := []*options.ClientOptions{
    options.Client().SetAuth(options.Credential{Username: "mongoadmin", Password: "secret"}),
    options.Client().ApplyURI(mongoUrl),
    options.Client().SetReadConcern(readconcern.Majority()),
    options.Client().SetWriteConcern(writeconcern.New(writeconcern.J(true), writeconcern.W(1)))}

    mongoClient, err := mongo.Connect(context.TODO(), options...)

    if err != nil {
    log.Fatalf("Client connect failed. error: %v", err)
    }
    client = mongoClient

    ctxForPing, cancel := context.WithTimeout(context.Background(), 1*time.Second)
    defer cancel()

    if err := client.Ping(ctxForPing, readpref.Primary()); err != nil {
    log.Fatalf("Client ping failed. error: %v", err)
    }

    userCollection = client.Database(database).Collection(collection)

    // index creation for text search
    model := mongo.IndexModel{Keys: bson.D{{Key: "name", Value: "text"}}}
    name, err := userCollection.Indexes().CreateOne(context.TODO(), model)
    if err != nil {
    log.Fatalf("Index create failed error: %v", err)
    }
    fmt.Println("Index Created by name: " + name)
    }

    func OnShutdown(ctx context.Context) error {
    log.Println("Shutting down")
    return client.Disconnect(ctx)
    }

    func CreateUser(ctx context.Context, user User) error {
    _, err := userCollection.InsertOne(ctx, user)
    if err != nil {
    return err
    }

    return nil
    }

    func UpsertUser(ctx context.Context, user User) error {
    filter := bson.D{{Key: ID, Value: user.ID}}
    opts := options.Replace().SetUpsert(true)
    _, err := userCollection.ReplaceOne(ctx, filter, user, opts)
    if err != nil {
    return err
    }

    return nil
    }

    func GetUser(ctx context.Context, id string) (*User, error) {
    filter := bson.D{{Key: ID, Value: id}}
    var user User
    err := userCollection.FindOne(ctx, filter).Decode(&user)

    if err == mongo.ErrNoDocuments {
    return nil, nil
    }

    if err != nil {
    return nil, err
    }

    return &user, nil
    }

    func SearchUserByName(ctx context.Context, nameQuery string) ([]*User, error) {
    filter := bson.D{{Key: "$text", Value: bson.D{{Key: "$search", Value: nameQuery}}}}
    options := options.Find().SetSort(bson.D{{Key: "name", Value: -1}})

    cursor, err := userCollection.Find(ctx, filter, options)
    if err != nil {
    return nil, err
    }

    result := []*User{}
    if err = cursor.All(ctx, &result); err != nil {
    return nil, err
    }

    return result, nil
    }

    func main() {
    mongoClientInitialize()
    OnShutdown(context.TODO())
    }