doufeng3602 2018-07-03 11:55
浏览 58
已采纳

如何编码/解码mongodb游标?

I need to build a list of "pages" so part of this there will be a cursor. The issue is that I can't find a way to encode(to string) and decode the cursor. Any idea? The Cursor interface has no "encoding" method(there is ID, though undocumented) and there is no way to create a new cursor from a string(or 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
}

Why do I need the cursor encoded?

To provide pagination to the end client through a html or JSON API.

  • 写回答

2条回答 默认 最新

  • dow58115 2018-07-04 12:43
    关注

    MongoDB does not provide a serializable cursor. Cursor is not serializable. The recommended workaround is to use a range query and sort on a field that generally changes in a consistent direction over time such _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;
    }
    

    There is a go package minquery that tries to make the cursor query/serialization more convenient. You may find it helpful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?