Skip to content

Instantly share code, notes, and snippets.

@varver
Forked from congjf/.Title
Created November 29, 2016 21:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save varver/39a325f647738a87d4e6dd71eb8c10f1 to your computer and use it in GitHub Desktop.
Save varver/39a325f647738a87d4e6dd71eb8c10f1 to your computer and use it in GitHub Desktop.
Using MongoDB in golang with mgo
Using MongoDB in golang with mgo
package main
import (
"fmt"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"time"
)
type Person struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Name string
Phone string
Timestamp time.Time
}
var (
IsDrop = true
)
func main() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
// Drop Database
if IsDrop {
err = session.DB("test").DropDatabase()
if err != nil {
panic(err)
}
}
// Collection People
c := session.DB("test").C("people")
// Index
index := mgo.Index{
Key: []string{"name", "phone"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err = c.EnsureIndex(index)
if err != nil {
panic(err)
}
// Insert Datas
err = c.Insert(&Person{Name: "Ale", Phone: "+55 53 1234 4321", Timestamp: time.Now()},
&Person{Name: "Cla", Phone: "+66 33 1234 5678", Timestamp: time.Now()})
if err != nil {
panic(err)
}
// Query One
result := Person{}
err = c.Find(bson.M{"name": "Ale"}).Select(bson.M{"phone": 0}).One(&result)
if err != nil {
panic(err)
}
fmt.Println("Phone", result)
// Query All
var results []Person
err = c.Find(bson.M{"name": "Ale"}).Sort("-timestamp").All(&results)
if err != nil {
panic(err)
}
fmt.Println("Results All: ", results)
// Update
colQuerier := bson.M{"name": "Ale"}
change := bson.M{"$set": bson.M{"phone": "+86 99 8888 7777", "timestamp": time.Now()}}
err = c.Update(colQuerier, change)
if err != nil {
panic(err)
}
// Push a item to the Array in the Collection by Collection's ObjectId
idQueryier := bson.ObjectIdHex("52b298f8b6bb960ff805ef3b")
change := bson.M{"$push": bson.M{"sections": bson.M{"name":"office"}}}
err = c.Update(idQuerier, change)
if err != nil {
panic(err)
}
// Query All
err = c.Find(bson.M{"name": "Ale"}).Sort("-timestamp").All(&results)
if err != nil {
panic(err)
}
fmt.Println("Results All: ", results)
}
import (
// native packages
"encoding/json"
"fmt"
"log"
"net/http"
// 3rd packages
"labix.org/v2/mgo/bson"
)
// Organizations数据模型结构
type Organizations struct {
Name string `json:"name"`
Area string `json:"area"`
Type string `json:"type"`
CustomerType string `json:"customertype"`
State string `json:"state"`
LastUpdated string `json:"lastupdated"`
Assigned string `json:"assigned"`
Address `json:"address"`
}
// for GET /Organizations
func (u *Organizations) Index(rw http.ResponseWriter, req *http.Request) {
var org Organizations
conditions := bson.M{"_id": bson.M{"$exist": 1}}
result, _ := org.Retrieve(conditions)
fmt.Fprint(rw, result)
}
// Organizations Find
func (o *Organizations) Retrieve(conditions map[string]interface{}) ([]Organizations, error) {
session, err := getSession()
if err != nil {
return nil, err
}
defer session.Close()
collection := session.DB(DATABASE).C("organizations")
result := []Organizations{}
err = collection.Find(conditions).All(&result)
if err != nil {
log.Println(err.Error())
return nil, err
}
return result, nil
}
// The projection parameter specifies which fields to return.
// http://docs.mongodb.org/manual/reference/method/db.collection.find/#projections
// db.products.find( { qty: { $gt: 25 } }, { item: 1, qty: 1 } )
// Or Query().select()
func (u Organizations) Index(rw http.ResponseWriter, req *http.Request) {
notice := "Organizations#Index:" + req.Method + req.URL.String()
log.Println(notice)
values := req.URL.Query()
var org model.Organizations
conditions := bson.M{"_id": bson.M{"$exists": true}}
if values.Get("name") != "" {
conditions["name"] = values.Get("name")
}
if values.Get("area") != "" {
conditions["area"] = values.Get("area")
}
if values.Get("type") != "" {
conditions["type"] = values.Get("type")
}
result, _ := org.Retrieve(conditions)
encoder := json.NewEncoder(rw)
err := encoder.Encode(result)
if err != nil {
log.Println(err.Error())
rw.WriteHeader(http.StatusInternalServerError)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment