【发布时间】:2016-11-02 19:31:21
【问题描述】:
我有一个这样的结构:
type SavedData struct {
ID bson.ObjectId `bson:"_id"`
Data string
Date time.Time
}
我也有我的
collection := database.C("coll_name")
如何检索此集合中最后插入的条目?
谢谢
【问题讨论】:
我有一个这样的结构:
type SavedData struct {
ID bson.ObjectId `bson:"_id"`
Data string
Date time.Time
}
我也有我的
collection := database.C("coll_name")
如何检索此集合中最后插入的条目?
谢谢
【问题讨论】:
显然 mongoDB 默认按照插入时间排序 this question 所以你可以像这样跳过集合的前 N 个元素。
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)
【讨论】:
接受的答案是 5 岁。这应该适用于今天的 mongodb 驱动程序
collection.FindOne(ctx, bson.M{"$natural": -1})
【讨论】:
unknown top level operator: $natural。你认为它会是什么?
如果你想获取集合中的最新文档,你必须使用 mongo-driver 选项
import(
...
"go.mongodb.org/mongo-driver/mongo/options"
)
myOptions := options.FindOne()
myOptions.SetSort(bson.M{"$natural":-1})
collection.FindOne(ctx, bson.M{}, myOptions)
【讨论】: