首页 > 解决方案 > 如何获取集合中的最后一个文档

问题描述

我正在尝试获取集合中的最后一个文档,但它一直以 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"
}

标签: mongodbgomongo-go

解决方案


你在正确的轨道上,你的解决方案几乎是完整的,缺少的是你必须在调用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
}

推荐阅读