mongodb - 如何编码/解码 mongodb 游标?

标签 mongodb go mongo-go

我需要建立一个“页面”列表,所以其中一部分会有一个 cursor .问题是我找不到编码(到字符串)和解码光标的方法。任何的想法? Cursor接口(interface)没有“编码”方法(有 ID,但未记录)并且无法从字符串(或 int)创建新游标。

type Cursor interface {

    // Get the ID of the cursor.
    ID() int64

    // Get the next result from the cursor.
    // Returns true if there were no errors and there is a next result.
    Next(context.Context) bool

    Decode(interface{}) error

    DecodeBytes() (bson.Reader, error)

    // Returns the error status of the cursor
    Err() error

    // Close the cursor.
    Close(context.Context) error
}

为什么我需要对光标进行编码?

通过 html 或 JSON API 为最终客户端提供分页。

最佳答案

MongoDB 不提供可序列化游标。 Cursor不可序列化。 recommended workaround是使用范围查询并对通常随时间以一致方向变化的字段进行排序,例如 _id

function printStudents(startValue, nPerPage) {
  let endValue = null;
  db.students.find( { _id: { $lt: startValue } } )
             .sort( { _id: -1 } )
             .limit( nPerPage )
             .forEach( student => {
               print( student.name );
               endValue = student._id;
             } );

  return endValue;
}

有一个go包minquery试图使游标查询/序列化更方便。您可能会发现它很有帮助。

关于mongodb - 如何编码/解码 mongodb 游标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51154010/

相关文章:

mongodb - 如何在解码 MongoDB 文档时忽略空值?

ruby-on-rails - 未定义的方法 'dragonfly_accessor'

html - 遍历多个表单值并将其中一些放入结构 slice 中

initialization - Go if 语句中的多个初始值设定项

arrays - $ concatArrays仅支持数组,不支持对象

mongo-go - 使用 mongodb-go-driver 如何获取内部异常

mongodb - 为启用身份验证的 mongodb 运行 mongostat 时出现问题

使用管道聚合的 Spring Data MongoDB 查找

MongoDB - 文本字段索引和文本索引之间的区别?

go - 是否可以使用bufio.Writer进行使用/写入?