douiwn6941 2016-02-27 15:29
浏览 97
已采纳

使用Golang和mgo从Collection MongoDB中获取元素

My task is writing chat with history. So for creating history i need each of messages send to Mongodb and when I have a next connecting I need to getting all messages and, with loop, send to all clients that are connected to chat

This is code of my ChatServer

func ChatServer(ws *websocket.Conn) {

// Connecting to MongoDB, collection History
session, err := mgo.Dial("mongodb://******:*******@ds045795.mongolab.com:45795/catalog")
if err != nil {
    panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("catalog").C("History")

// fmt.Println(c.Find())
// Adding clients to the map
clientId := ws.RemoteAddr().String()
defer ws.Close()
clients[ws] = true

// Loop for receiving msg
for {
    var msg string
    // If can not read msg - delete client from map
    if err := websocket.Message.Receive(ws, &msg); err != nil {
        delete(clients, ws)
        return
    }
    sendAll(msg)
    err = c.Insert(&Connect{clientId, msg})
    if err != nil {
        log.Fatal(err)
    }
}
}

So my problem is getting all the elements in order from the collection. I have no idea how to do it, because can not find the proper function in documentations. Maybe you have some other offers?

  • 写回答

1条回答 默认 最新

  • doqp87012 2016-02-27 19:46
    关注

    First of all I agree with commenters above - you should add timestamp to your Connect structure. But even without it you can sort your entries by ObjectID as part of it is timestamp. Yes this is quite dirty way and may cause issues if you use sharding or transfer database to another server but in your case (single Mongolab instance) it's possible with something like like (I don't know your structure so "ip" and "message" are just assumptions)

    var connects []Connect
    c.Find(bson.M{"ip": "127.0.0.1"}).Sort("-_id").Limit(50).All(&connects) // 50 entries in desc order
    
    for _, connect := range connects {
        log.Println(connect.Message)
    }
    

    But really add time to your Connect like that

    package main
    
    import (
        "fmt"
        "gopkg.in/mgo.v2"
        "gopkg.in/mgo.v2/bson"
        "log"
        "time"
    )
    
    type Connect struct {
        Ip      string
        Message string
        Ts      time.Time
    }
    
    func main() {
        session, err := mgo.Dial("mongodb://souser:123456@ds055855.mlab.com:55855/catalog")
    
        if err != nil {
            panic(err)
        }
        defer session.Close()
        session.SetMode(mgo.Monotonic, true)
    
        c := session.DB("catalog").C("History")
    
        for i := 0; i < 100; i++ {
            c.Insert(&Connect{"127.0.0.2", fmt.Sprintf("Test message #%d", i), time.Now()})
            if err != nil {
                log.Fatal(err)
            }
        }
    
        var connects []Connect
        c.Find(bson.M{"ip": "127.0.0.2"}).Sort("-ts").Limit(50).All(&connects)
    
        for _, connect := range connects {
            log.Println(connect.Message)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?