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