dougu1990 2017-11-24 09:37
浏览 1592
已采纳

如何使用golang获取mongodb中数组中的最后一个元素?

I'm working in go language. I'm using mgo driver to get the data from mongodb. I want last entry from the events array.

There will be huge data in future. so I don't want to read the whole record but just want specific data from the record.

db.events.find({"_id":"59ce53b9-970a-44a2-8419-b41a99120b25"},{"events":{$slice:-1}}).pretty()

this is working in mongo shell. I want this to work in go lang.

This is the sample data, from which I want last entry present in events.

    {
    "_id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
    "version" : 9,
    "events" : [
        {
            "event_type" : "customer:added",
            "data" : {
                "id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
                "name" : "arjun"
            },
            "timestamp" : ISODate("2017-11-20T12:21:34.910Z"),
            "aggregate_type" : "customer",
            "_id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
            "version" : 1
        },
        {
            "event_type" : "customer:address-updated",
            "data" : {
                "id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
                "address" : "bangalore"
            },
            "timestamp" : ISODate("2017-11-20T12:22:08.496Z"),
            "aggregate_type" : "customer",
            "_id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
            "version" : 2
        }
    ]
}
  • 写回答

1条回答

  • douyou1857 2017-11-24 10:49
    关注

    What you pass as the 2nd argument to find() is a projection.

    Projections in mgo can be specified using the Query.Select() method.

    So your query in mgo simply looks like this:

    sess := ... // Acquire MongoDB session
    c := sess.DB("dbname").C("events")
    
    var doc bson.M
    
    err := c.FindId("59ce53b9-970a-44a2-8419-b41a99120b25").
        Select(bson.M{"events": bson.M{"$slice": -1}}).
        One(&doc)
    
    if err != nil {
        // Handle error
    }
    fmt.Println(len(doc["events"].([]interface{}))) // This prints 1
    fmt.Println(doc)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数