mongodb - 如何获取集合中的最后一个文档
问题描述
我正在尝试获取集合中的最后一个文档,但它一直以 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
}
推荐阅读
- jquery - 切换导航重叠问题
- regex - 给定项目列表不起作用时使用正则表达式的 Ansible 替换模块
- python - 选择列表/列/数组的每第 n 个子集
- android - 在视图中填充线性布局,无法在 android 的文本框中显示值
- apache-spark - 有没有办法使用 spark-cassandra 连接器访问 Cassandra 模式信息?
- python - IF 语句忽略键盘输入
- python-2.7 - 岩石检测,我无法检测到所有岩石
- java - 需要 yml 文件的指导
- java - 使用位操作验证 ascii 字符串是否包含唯一字符,而不使用其他数据结构
- csv - CSV - 如何匹配相似的数据并将文件与批处理合并?