从GoLang中的mongodb获取最后插入的元素 [英] Get last inserted element from mongodb in GoLang

查看:54
本文介绍了从GoLang中的mongodb获取最后插入的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的结构:

type SavedData struct {
    ID   bson.ObjectId `bson:"_id"`
    Data string
    Date time.Time
}

我也有我的

collection := database.C("coll_name")

如何检索此集合中最后插入的条目?

How do I retrieve the last inserted entry in this collection ?

谢谢

推荐答案

显然,默认情况下,mongoDB默认根据插入时间进行排序,具体取决于此问题,因此您可以跳过以下内容的前N个元素这样的收藏.

Apparently mongoDB is by default sorted by insertion time according to this question so you can just skip the first N elements of the collection like so.

var myData SavedData 
dbSize, err := collection.Count()
if err != nil {
        return err
}

err = c.Find(nil).skip(dbSize-1).One(&myData)
if err != nil {
        return err
}

或者您可以反向搜索

c.Find(bson.M{ "$natural": -1 }).One(&myData)

这篇关于从GoLang中的mongodb获取最后插入的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆