本文整理汇总了Golang中launchpad/net/mgo.Mongo函数的典型用法代码示例。如果您正苦于以下问题:Golang Mongo函数的具体用法?Golang Mongo怎么用?Golang Mongo使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Mongo函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: loadNewsItem
func loadNewsItem(path string) ([]*NewsItem, os.Error) {
var item *NewsItem
items := make([]*NewsItem, 1)
cachedItem, found := cachedNewsItems[path]
if found {
t := time.Seconds()
if (t - cachedItem.CachedAt) < (60 * 10) { // cache for 10 minutes
items[0] = cachedItem.NewsItem
return items, nil
}
}
mongo, err := mgo.Mongo("localhost")
if err != nil {
return nil, err
}
defer mongo.Close()
c := mongo.DB(*database).C("newsitems")
item = &NewsItem{}
err = c.Find(bson.M{"page.permalink": path}).One(item)
go cacheNewsItem(item)
items[0] = item
return items, err
}
示例2: TestRemoveAll
func (s *S) TestRemoveAll(c *C) {
session, err := mgo.Mongo("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
coll := session.DB("mydb").C("mycoll")
ns := []int{40, 41, 42, 43, 44, 45, 46}
for _, n := range ns {
err := coll.Insert(M{"n": n})
c.Assert(err, IsNil)
}
err = coll.RemoveAll(M{"n": M{"$gt": 42}})
c.Assert(err, IsNil)
result := &struct{ N int }{}
err = coll.Find(M{"n": 42}).One(result)
c.Assert(err, IsNil)
c.Assert(result.N, Equals, 42)
err = coll.Find(M{"n": 43}).One(result)
c.Assert(err, Equals, mgo.NotFound)
err = coll.Find(M{"n": 44}).One(result)
c.Assert(err, Equals, mgo.NotFound)
}
示例3: TestFindIterTwiceWithSameQuery
func (s *S) TestFindIterTwiceWithSameQuery(c *C) {
session, err := mgo.Mongo("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
coll := session.DB("mydb").C("mycoll")
for i := 40; i != 47; i++ {
coll.Insert(M{"n": i})
}
query := coll.Find(M{}).Sort(M{"n": 1})
result1, err := query.Skip(1).Iter()
c.Assert(err, IsNil)
result2, err := query.Skip(2).Iter()
c.Assert(err, IsNil)
result := struct{ N int }{}
err = result2.Next(&result)
c.Assert(err, IsNil)
c.Assert(result.N, Equals, 42)
err = result1.Next(&result)
c.Assert(err, IsNil)
c.Assert(result.N, Equals, 41)
}
示例4: TestEnsureIndexDropIndex
func (s *S) TestEnsureIndexDropIndex(c *C) {
session, err := mgo.Mongo("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
coll := session.DB("mydb").C("mycoll")
err = coll.EnsureIndexKey([]string{"a"})
c.Assert(err, IsNil)
err = coll.EnsureIndexKey([]string{"-b"})
c.Assert(err, IsNil)
err = coll.DropIndex([]string{"-b"})
c.Assert(err, IsNil)
sysidx := session.DB("mydb").C("system.indexes")
dummy := &struct{}{}
err = sysidx.Find(M{"name": "a_1"}).One(dummy)
c.Assert(err, IsNil)
err = sysidx.Find(M{"name": "b_1"}).One(dummy)
c.Assert(err, Equals, mgo.NotFound)
err = coll.DropIndex([]string{"a"})
c.Assert(err, IsNil)
err = sysidx.Find(M{"name": "a_1"}).One(dummy)
c.Assert(err, Equals, mgo.NotFound)
err = coll.DropIndex([]string{"a"})
c.Assert(err, Matches, "index not found")
}
示例5: TestMapReduceFinalize
func (s *S) TestMapReduceFinalize(c *C) {
session, err := mgo.Mongo("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
coll := session.DB("mydb").C("mycoll")
for _, i := range []int{1, 4, 6, 2, 2, 3, 4} {
coll.Insert(M{"n": i})
}
job := mgo.MapReduce{
Map: "function() { emit(this.n, 1) }",
Reduce: "function(key, values) { return Array.sum(values) }",
Finalize: "function(key, count) { return {count: count} }",
}
var result []struct {
Id int "_id"
Value struct{ Count int }
}
_, err = coll.Find(nil).MapReduce(job, &result)
c.Assert(err, IsNil)
expected := map[int]int{1: 1, 2: 2, 3: 1, 4: 2, 6: 1}
for _, item := range result {
c.Logf("Item: %#v", &item)
c.Assert(item.Value.Count, Equals, expected[item.Id])
expected[item.Id] = -1
}
}
示例6: TestSort
func (s *S) TestSort(c *C) {
session, err := mgo.Mongo("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
coll := session.DB("mydb").C("mycoll")
coll.Insert(M{"a": 1, "b": 1})
coll.Insert(M{"a": 2, "b": 2})
coll.Insert(M{"a": 2, "b": 1})
coll.Insert(M{"a": 0, "b": 1})
coll.Insert(M{"a": 2, "b": 0})
coll.Insert(M{"a": 0, "b": 2})
coll.Insert(M{"a": 1, "b": 2})
coll.Insert(M{"a": 0, "b": 0})
coll.Insert(M{"a": 1, "b": 0})
query := coll.Find(M{})
query.Sort(bson.D{{"a", -1}}) // Should be ignored.
iter, err := query.Sort(bson.D{{"b", -1}, {"a", 1}}).Iter()
c.Assert(err, IsNil)
l := make([]int, 18)
r := struct{ A, B int }{}
for i := 0; i != len(l); i += 2 {
err := iter.Next(&r)
c.Assert(err, IsNil)
l[i] = r.A
l[i+1] = r.B
}
c.Assert(l, Equals,
[]int{0, 2, 1, 2, 2, 2, 0, 1, 1, 1, 2, 1, 0, 0, 1, 0, 2, 0})
}
示例7: TestSafeSetting
func (s *S) TestSafeSetting(c *C) {
session, err := mgo.Mongo("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()
// Check the default
safe := session.Safe()
c.Assert(safe.W, Equals, 0)
c.Assert(safe.WTimeout, Equals, 0)
c.Assert(safe.FSync, Equals, false)
// Tweak it
session.SetSafe(&mgo.Safe{W: 1, WTimeout: 2, FSync: true})
safe = session.Safe()
c.Assert(safe.W, Equals, 1)
c.Assert(safe.WTimeout, Equals, 2)
c.Assert(safe.FSync, Equals, true)
// Reset it again.
session.SetSafe(&mgo.Safe{})
safe = session.Safe()
c.Assert(safe.W, Equals, 0)
c.Assert(safe.WTimeout, Equals, 0)
c.Assert(safe.FSync, Equals, false)
// Ensure safety to something higher.
session.SetSafe(&mgo.Safe{W: 5, WTimeout: 6, FSync: true})
safe = session.Safe()
c.Assert(safe.W, Equals, 5)
c.Assert(safe.WTimeout, Equals, 6)
c.Assert(safe.FSync, Equals, true)
// Ensure safety to something less conservative won't change it.
session.EnsureSafe(&mgo.Safe{W: 4, WTimeout: 7, FSync: false})
safe = session.Safe()
c.Assert(safe.W, Equals, 5)
c.Assert(safe.WTimeout, Equals, 6)
c.Assert(safe.FSync, Equals, true)
// But to something more conservative will.
session.EnsureSafe(&mgo.Safe{W: 6, WTimeout: 4})
safe = session.Safe()
c.Assert(safe.W, Equals, 6)
c.Assert(safe.WTimeout, Equals, 4)
c.Assert(safe.FSync, Equals, true)
// EnsureSafe with nil does nothing.
session.EnsureSafe(nil)
safe = session.Safe()
c.Assert(safe.W, Equals, 6)
c.Assert(safe.WTimeout, Equals, 4)
c.Assert(safe.FSync, Equals, true)
// Changing the safety of a cloned session doesn't touch the original.
clone := session.Clone()
defer clone.Close()
clone.EnsureSafe(&mgo.Safe{W: 100})
safe = session.Safe()
c.Assert(safe.W, Equals, 6)
}
示例8: TestDirect
func (s *S) TestDirect(c *C) {
session, err := mgo.Mongo("localhost:40012?connect=direct")
c.Assert(err, IsNil)
defer session.Close()
// We know that server is a slave.
session.SetMode(mgo.Monotonic, true)
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(strings.HasSuffix(result.Host, ":40012"), Equals, true)
stats := mgo.GetStats()
c.Assert(stats.SocketsAlive, Equals, 1)
c.Assert(stats.SocketsInUse, Equals, 1)
c.Assert(stats.SocketRefs, Equals, 1)
// We've got no master, so it'll timeout.
session.SetSyncTimeout(5e8)
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"test": 1})
c.Assert(err, Matches, "no reachable servers")
// Slave is still reachable.
result.Host = ""
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(strings.HasSuffix(result.Host, ":40012"), Equals, true)
}
示例9: TestGridFSOpen
func (s *S) TestGridFSOpen(c *C) {
session, err := mgo.Mongo("localhost:40011")
c.Assert(err, IsNil)
defer session.Close()
db := session.DB("mydb")
gfs := db.GridFS("fs")
file, err := gfs.Create("myfile.txt")
c.Assert(err, IsNil)
file.Write([]byte{'1'})
file.Close()
file, err = gfs.Create("myfile.txt")
c.Assert(err, IsNil)
file.Write([]byte{'2'})
file.Close()
file, err = gfs.Open("myfile.txt")
c.Assert(err, IsNil)
defer file.Close()
var b [1]byte
_, err = file.Read(b[:])
c.Assert(err, IsNil)
c.Assert(string(b[:]), Equals, "2")
}
示例10: TestPrimaryShutdownStrong
func (s *S) TestPrimaryShutdownStrong(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Mongo("localhost:40021")
c.Assert(err, IsNil)
defer session.Close()
// With strong consistency, this will open a socket to the master.
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
// Kill the master.
host := result.Host
s.Stop(host)
// This must fail, since the connection was broken.
err = session.Run("serverStatus", result)
c.Assert(err, Equals, io.EOF)
// With strong consistency, it fails again until reset.
err = session.Run("serverStatus", result)
c.Assert(err, Equals, io.EOF)
session.Refresh()
// Now we should be able to talk to the new master.
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(result.Host, Not(Equals), host)
}
示例11: TestPrimaryShutdownEventual
func (s *S) TestPrimaryShutdownEventual(c *C) {
if *fast {
c.Skip("-fast")
}
session, err := mgo.Mongo("localhost:40021")
c.Assert(err, IsNil)
defer session.Close()
result := &struct{ Host string }{}
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
master := result.Host
session.SetMode(mgo.Eventual, true)
// Should connect to the master when needed.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
// Kill the master.
s.Stop(master)
// Should still work, with the new master now.
coll = session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
err = session.Run("serverStatus", result)
c.Assert(err, IsNil)
c.Assert(result.Host, Not(Equals), master)
}
示例12: TestSetModeMonotonicAfterStrong
func (s *S) TestSetModeMonotonicAfterStrong(c *C) {
// Test that a strong session shifting to a monotonic
// one preserves the socket untouched.
session, err := mgo.Mongo("localhost:40012")
c.Assert(err, IsNil)
defer session.Close()
// Insert something to force a connection to the master.
coll := session.DB("mydb").C("mycoll")
err = coll.Insert(M{"a": 1})
c.Assert(err, IsNil)
session.SetMode(mgo.Monotonic, false)
// Wait since the sync also uses sockets.
for len(session.LiveServers()) != 3 {
c.Log("Waiting for cluster sync to finish...")
time.Sleep(5e8)
}
// Master socket should still be reserved.
stats := mgo.GetStats()
c.Assert(stats.SocketsInUse, Equals, 1)
// Confirm it's the master even though it's Monotonic by now.
result := M{}
cmd := session.DB("admin").C("$cmd")
err = cmd.Find(M{"ismaster": 1}).One(&result)
c.Assert(err, IsNil)
c.Assert(result["ismaster"], Equals, true)
}
示例13: Test
// test function to test that MongoDB works
func Test() {
log.Println("DB Test")
session, err := mgo.Mongo("localhost")
if err != nil {
panic(err)
}
defer session.Close()
//db.Run(mgo.D{{"create", "mycollection"}, {"size", 1024}})
c := session.DB("try").C("try")
err = c.Insert(&Server{Id: 1, Name: "kcode.de"}, &Server{Id: 2, Name: "MyServer 3 [Dedicated]"})
if err != nil {
panic(err)
}
result := Server{}
qry := c.Find(bson.M{"id": 1})
err = qry.One(&result)
if err != nil {
panic(err)
}
log.Println(result)
var result2 *Server
qry.For(&result2, func() os.Error {
//fmt.Printf("r2: %v\n", result2)
fmt.Printf("r2: %d %s\n", result2.Id, result2.Name)
return nil
})
}
示例14: init
func init() {
var err error
session, err = mgo.Mongo(Env("MONGO_URL", "localhost"))
if err != nil {
log.Fatal(err)
}
}
示例15: main
func main() {
flag.Parse()
go hub()
var err error
session, err = mgo.Mongo("localhost")
if err != nil {
panic("main > Mongo: " + err.Error())
}
defer session.Close()
pfx := "/static/"
h := http.StripPrefix(pfx, http.FileServer(http.Dir("../static/")))
http.Handle(pfx, h) // It is absurd I had to work that hard to serve static files. Let's shove them on AWS or something and forget about it
http.HandleFunc("/tickle", doTickle)
http.HandleFunc("/keys", viewKeys)
http.HandleFunc("/keys/add", addKey)
http.HandleFunc("/keys/check", checkKey)
http.HandleFunc("/links/send", sendLink)
http.HandleFunc("/register", registerHandler)
http.HandleFunc("/openid/callback", openID)
http.HandleFunc("/openid/callback/chrome", openID)
http.HandleFunc("/users/validate", validateUser)
http.HandleFunc("/logout", doLogout)
http.HandleFunc("/login", doLogin)
http.HandleFunc("/links/", linksList)
http.HandleFunc("/", rootHandler)
http.Handle("/ws", websocket.Handler(wsHandler))
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}