【问题标题】:Getting the elements from Collection MongoDB using Golang and mgo使用 Golang 和 mgo 从 Collection MongoDB 中获取元素
【发布时间】:2016-02-27 15:29:56
【问题描述】:

我的任务是写历史聊天。因此,为了创建历史记录,我需要将每条消息发送到 Mongodb,当我有下一次连接时,我需要获取所有消息,并通过循环发送给所有连接到聊天的客户端

这是我的聊天服务器的代码

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)
    }
}
}

所以我的问题是按顺序从集合中获取所有元素。 我不知道该怎么做,因为在文档中找不到合适的功能。 也许您还有其他优惠?

【问题讨论】:

  • 您没有在消息中插入时间戳?
  • 不,我没有插入时间戳
  • 那么“顺序”是如何确定的呢?自动?
  • 集合中的索引,但我不知道如何检测集合的长度和文档的索引

标签: mongodb go chat mgo


【解决方案1】:

首先,我同意上述评论者的观点 - 您应该在 Connect 结构中添加时间戳。但即使没有它,您也可以按 ObjectID 对条目进行排序,因为它是时间戳的一部分。是的,这是一种很肮脏的方式,可能cause issues if you use sharding or transfer database to another server,但在你的情况下(单个Mongolab实例)可能有类似的东西(我不知道你的结构,所以“ip”和“消息”只是假设)

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)
}

但真的要像这样为您的Connect 添加时间

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)
    }
}

【讨论】:

  • 上一个问题你好。正如我对某个 ip 的理解,我想以这样的顺序显示集合中的所有消息:MongoLab Order 也许我不明白什么...
  • @ВладДарьев c.Find(bson.M{}).Sort("_id").All(&amp;connects)
  • 再次非常感谢你)),也许我可以问你有时不在stackoverflow中吗?你能不能给我你的联系方式(邮件或其他),当然,如果你不反对因为你在两天内第二次帮助了我))
猜你喜欢
  • 1970-01-01
  • 2021-04-18
  • 2019-05-09
  • 1970-01-01
  • 1970-01-01
  • 2016-11-02
  • 2012-10-20
  • 1970-01-01
  • 2017-12-30
相关资源
最近更新 更多