Skip to content

Instantly share code, notes, and snippets.

@lotusirous
Last active April 25, 2019 00:01
Show Gist options
  • Select an option

  • Save lotusirous/045413528c66ebb37cd7952e19919663 to your computer and use it in GitHub Desktop.

Select an option

Save lotusirous/045413528c66ebb37cd7952e19919663 to your computer and use it in GitHub Desktop.
An example of manipulate data in mongodb with golang
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
// User defines an entity for our database
type User struct {
Name string `bson:"name"`
ID int32 `bson:"ID"`
Age int16 `bson:"age"`
}
// UserRepository defines a store for manipulate data
type UserRepository struct {
ctx context.Context
collection *mongo.Collection
}
// InsertOne inserts a user struct
func (ur *UserRepository) InsertOne(user User) error {
_, err := ur.collection.InsertOne(ur.ctx, user)
// log.Print(result)
return err
}
// FindOneByID returns a user struct and error
func (ur *UserRepository) FindOneByID(id int16) (User, error) {
var r User
filter := bson.M{"ID": id}
err := ur.collection.FindOne(ur.ctx, filter).Decode(&r)
return r, err
}
// FindAgeSmallerThan demonstrates an array in return from mongo query
func (ur *UserRepository) FindAgeSmallerThan(age int16) ([]*User, error) {
var results []*User
filter := bson.M{"age": bson.M{"$lt": 6}}
cursor, err := ur.collection.Find(ur.ctx, filter)
if err != nil {
return results, err
}
for cursor.Next(ur.ctx) {
var user User
err := cursor.Decode(&user)
check(err)
results = append(results, &user)
}
if err := cursor.Err(); err != nil {
return results, cursor.Err()
}
return results, nil
}
func main() {
// Connect to database
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
check(err)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
defer cancel()
// process users collection
collection := client.Database("test").Collection("users")
repo := UserRepository{ctx: ctx, collection: collection}
// Insert user
err = repo.InsertOne(User{Name: "foo", ID: 1, Age: 10})
check(err)
// Find user by ID field
user, err := repo.FindOneByID(1)
check(err)
log.Print(user)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment