Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
mgo example
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)
}
// Query All
err = c.Find(bson.M{"name": "Ale"}).Sort("-timestamp").All(&results)
if err != nil {
panic(err)
}
fmt.Println("Results All: ", results)
}
@btfak

This comment has been minimized.

Copy link

btfak commented Nov 21, 2013

hi, how to get data from a period of time ?

@grennis

This comment has been minimized.

Copy link

grennis commented Jul 12, 2014

So many of these:

if err != nil {
panic(err)
}

How easy it is to forget or overlook this. I would like to hear the explanation of why this is not a problem with Go and it doesn't need exceptions.

@AustinDizzy

This comment has been minimized.

Copy link

AustinDizzy commented Jul 30, 2014

@grennis These errors can be discarded on creation if you wanted to. Replacing err with _ would automatically ditch the output and rid your program of error handling, leaving the developer up to the choice of fully debugging with working tests to prevent those errors or writing their own error handling functions. (e.g. _ = c.Find(bson.M{"name": "Ale"}).Sort("-timestamp").All(&results))

Those err != nil conditionals can also be completely replaced with a PanicErr(err) function, placing the conditional in the PanicErr function to clean up the error handling conditionals if necessary.

But, like I said, if you don't care about your errors then you can automatically discard them with _.

@nadeemelahi

This comment has been minimized.

Copy link

nadeemelahi commented Aug 11, 2014

Excellent.
Thx for posting.

@geraldstanje

This comment has been minimized.

Copy link

geraldstanje commented Sep 15, 2014

how can you query all people in the table?

@molivier

This comment has been minimized.

Copy link

molivier commented Apr 24, 2015

@geraldstanje to query all people in the table you can do :

err = c.Find(nil).Sort("-timestamp").All(&results)
if err != nil {
    panic(err)
}
fmt.Println("Results All: ", results)
@kalashnikov

This comment has been minimized.

Copy link

kalashnikov commented Jun 13, 2015

In my case, var results []Person gave me empty result.

Instead, below solution works. Reference

var m []bson.M
_ = c.Find(nil).All(&m)
for _, v := range m {
    fmt.Println(v)
}
@nguyenthenguyen

This comment has been minimized.

Copy link

nguyenthenguyen commented Jul 14, 2015

c.Insert(&Person{Name: "Ale", Phone: "+55 53 1234 4321", Timestamp: time.Now()})
Mongodb auto generate _id, how to get it?

@d4rk5eed

This comment has been minimized.

Copy link

d4rk5eed commented Aug 1, 2015

@nguyenthenguyen if you assign Person{Name: "Ale", Phone: "+55 53 1234 4321", Timestamp: time.Now()} to variable, for example person. Pass this variable to Insert function and after success execution you get person.Id

@d4rk5eed

This comment has been minimized.

Copy link

d4rk5eed commented Aug 1, 2015

@nguyenthenguyen sorry, I misled you.
After some research I found working one

type Person struct {
    ID        bson.ObjectId `bson:"_id,omitempty"`
    Name      string
    Phone     string
    Timestamp time.Time
}
//....
id = bson.NewObjectId()
c.Insert(&Person{ID: id, Name: "Ale", Phone: "+55 53 1234 4321", Timestamp: time.Now()})

You get correct mongo id in id

@prsolucoes

This comment has been minimized.

Copy link

prsolucoes commented Aug 14, 2015

Can you post example of update by ID ?

@xuqingfeng

This comment has been minimized.

Copy link

xuqingfeng commented Aug 25, 2015

@prsolucoes

err := c.UpdateId(id, bson.M{"$set": bson.M{"name": "updated name"}})
@littlechad

This comment has been minimized.

Copy link

littlechad commented Nov 8, 2015

how do you know if its empty, i take it the this

if err != nil {
    panic(err)
}

doesn't necessarily mean that it is empty, does it?

nevermind, i would just do a Count()

@EwanValentine

This comment has been minimized.

Copy link

EwanValentine commented Nov 30, 2015

Thanks for these examples, they've been incredibly useful. Does anyone have any examples on insert subdocuments? Say if I had

type Article struct {
    Title string `form"title" json:"title"`
    Categories []*Category
}

How would I go about finding an article, and adding a category?

Thanks!

@suwarnold

This comment has been minimized.

Copy link

suwarnold commented Apr 11, 2016

Hi guys,
If i have probably 4 server of mongodb. 1 server active(main), and the others server are slave which the active(main) server somehow can switch as slave, and slave can switch as active(main) automatic . how i develop the code to get only the active(main) server only? active(main) server means you can do add, remove, find process in that server only. Thanks before.

@testarossaaaaa

This comment has been minimized.

Copy link

testarossaaaaa commented May 5, 2016

@suwarnold, look at mgo.DialInfo{} and mgo.DialWithInfo()

@bsaideepak

This comment has been minimized.

Copy link

bsaideepak commented May 15, 2016

Thank You for the post!

@shackra

This comment has been minimized.

Copy link

shackra commented Aug 16, 2016

for some reason, c.Insert() insert nothing and no error is returned :S

@sandyydk

This comment has been minimized.

Copy link

sandyydk commented Sep 29, 2016

Hi All
change := bson.M{"$set": bson.M{"phone": "+86 99 8888 7777", "timestamp": time.Now()}}
I didn't get this part -- $set. What type is it? Or what are the other options in this?
I found this in docs --

change := mgo.Change{
        Update: bson.M{"$inc": bson.M{"n": 1}},
        ReturnNew: true,
}
info, err = col.Find(M{"_id": id}).Apply(change, &doc)
fmt.Println(doc.N)

I suppose inc stands for increment. But am not clear about the data type here(Interface?). Anyways again I suppose this is a fixed thing? But then that would contradict the next usage of bson.M...
Thanks in advance.

@mj073

This comment has been minimized.

Copy link

mj073 commented Nov 30, 2016

My Observation about UpdateAll() is, by default it upserts the record..
that means, if "phone" field from the change is not present in record, it will insert the field

change:= bson.M{"$set":bson.M{"phone": "+86 99 8888 7777", "timestamp": time.Now()}}

Is there a way to override the default upsert behaviour of UpdateAll() call ?

@iamclaytonray

This comment has been minimized.

Copy link

iamclaytonray commented Jun 27, 2017

You can also do

if err := c.Update(colQuerier, change); err != nil {
  // panic(err) <-- one way, or:
  w.WriteHeader(404)
  return
}
@ShambhaviAdokar

This comment has been minimized.

Copy link

ShambhaviAdokar commented Aug 3, 2017

Hi All,
I am trying to access the record but its returning me empty record
code:
result := Person{}

	err = c.Find(bson.M{"first_name": "ABC"}).Select(bson.M{"userEmail": 1}).One(&result)
	if err != nil {
		panic(err)
	}
	fmt.Println("Email", result)

output :
Email { }

please help.

@LordRahl90

This comment has been minimized.

Copy link

LordRahl90 commented Dec 7, 2017

Thanks for posting... learnt a lot..

Please is there a way to chain queries??? like where firstname is "anything" and lastname is "anything as well"

Thanks

@bussiere

This comment has been minimized.

Copy link

bussiere commented Apr 4, 2018

Thanks a lot

@neepoo

This comment has been minimized.

Copy link

neepoo commented Apr 16, 2019

thanks

@gaspan

This comment has been minimized.

Copy link

gaspan commented Jul 22, 2019

how to connect mongodb+srv ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.