gmob

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2021 License: MIT Imports: 7 Imported by: 0

README

Gmob

GoDoc Test Go Report Card

Gmob is simple util for MongoDB Go Driver to quickly build an unordered representation of a BSON document (M) from Map or Struct.

Install

go get -u github.com/tungquach/gmob

Usage

package main

import (
    ...
    github.com/tungquach/gmob
    ...
)

// Car example entity
type Car struct {
    ID string `bson:"_id"`
    Name string `bson:"name"`
    CreatedAt time.Time `bson:"createdAt"`
}

func main() {
    // connect to mongodb
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    client, err := mongo.Connect(context.TODO(), clientOptions)
    if err != nil {
        log.Fatal(err)
    }

    // cars collection
    ctx := context.Background()
    collection := client.Database("test").Collection("cars")

    // find record
    filter, _ := gmob.Build(Car{Name: "BMW"})
    result := &Car{}
    err = collection.FindOne(ctx, filter).Decode(result)
    log.Printf("result %+v, err: %v", result, err)

    // update record
    setValues, _ := gmob.Build(Car{Name: "BMW 2020"})
    err := collection.FindOneAndUpdate(ctx, bson.M{"_id": "car001"},
        bson.M{"$set": setValues}).Err()
    log.Printf("err: %v", err)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Build

func Build(in interface{}) (result bson.M, err error)

Build Mongo Driver BSON document (M) from Map and Struct. For Struct input, all fields must have "bson" tag, and returned result will not include fields with zero values like false, "", and 0, if you want keep zero values use Map instead.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL