mongodb - 您如何获取集合中的最后一个文档

标签 mongodb go mongo-go

我正在尝试获取集合中的最后一个文档,但它一直返回nil或EOF。我认为我走了正确的路,但是我不确定如何在Go中获取集合中的最后一个文档。这是我尝试获取的当前代码:

collection := client.Collection("quotes")

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

findOptions := options.Find()
findOptions.SetSort(bson.D{{"_id", -1}})
findOptions.SetLimit(1)

var lastQuote *model.Quote
cursor, err := collection.Find(ctx, bson.D{}, findOptions)
if err != nil {
    return "", "could not find last quote"
}
if err = cursor.Decode(&lastQuote); err != nil {
    fmt.Println(err) //returns EOF or nil if its Decode lastQuote
    return "", "could not obtain last quote"
}

最佳答案

您处在正确的轨道上,并且您的解决方案已接近完成,所缺少的是您必须先调用 Cursor.Next() ,然后再调用 Cursor.Decode()
mongo.Cursor 有点像迭代器,Cursor.Next()是前进到下一个迭代和下一个文档的东西。 Cursor.Next()返回一个bool值,该值指示是否存在一个新文档,您可以使用Cursor.Decode()对其进行解码。
所以这样做:

var lastQuote *model.Quote
cursor, err := collection.Find(ctx, bson.D{}, findOptions)
if err != nil {
    return "", "could not find last quote"
}
if !cursor.Next() {
    return "", "there were no documents"
}
if err = cursor.Decode(&lastQuote); err != nil {
    fmt.Println(err) //returns EOF or nil if its Decode lastQuote
    return "", "could not obtain last quote"
}
还要注意,如果要查询单个文档,使用 Collection.FindOne() 会更加简单和方便,如下所示:
opts := options.FindOne()
opts.SetSort(bson.D{{"_id", -1}})

if err := collection.FindOne(ctx, bson.D{}, opts).Decode(&lastQuote); err != nil {
    // Handle error
}

关于mongodb - 您如何获取集合中的最后一个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64887757/

相关文章:

mongodb - 如何使用默认集合和数据创建 Mongo Docker 镜像?

java - 我如何直接访问嵌入文档对象mongodb

javascript - 如何比较数组并计算匹配项

mongodb - 多个 session.Copy() 后 mgo 连接泄漏

xml - 将嵌套的 xml 解码为结构

javascript - Mongodb Node.js 获取插入文档的计数

go - 如何在 Bazel 中将 Google API 与 Go 结合使用

go - 如何从mongo-go-driver光标获取ObjectID为String?

mongodb - 将字符串 slice 转换为 BSON 数组

mongodb - mongo-go-driver获取插入的文档