Docs HomeMongoDB Manual

Tailable Cursors可尾随游标

By default, MongoDB will automatically close a cursor when the client has exhausted all results in the cursor. 默认情况下,当客户端用完游标中的所有结果时,MongoDB会自动关闭游标。However, for capped collections you may use a Tailable Cursor that remains open after the client exhausts the results in the initial cursor. 但是,对于封顶集合,您可以使用可尾随游标,该游标在客户端耗尽初始游标中的结果后保持打开状态。Tailable cursors are conceptually equivalent to the tail Unix command with the -f option (i.e. with "follow" mode). 可尾随游标在概念上等同于带有-f选项的tail Unix命令(即带有“follow”模式)。After clients insert new additional documents into a capped collection, the tailable cursor will continue to retrieve documents.在客户端将新的附加文档插入到有上限的集合中后,可裁剪游标将继续检索文档。

Use tailable cursors on capped collections that have high write volumes where indexes aren't practical. 在索引不实用的情况下,对具有高写入量的带帽集合使用可裁剪的游标。For instance, MongoDB replication uses tailable cursors to tail the primary's oplog.例如,MongoDB复制使用可跟踪的游标来跟踪primaryoplog

Note

If your query is on an indexed field, do not use tailable cursors, but instead, use a regular cursor. 如果查询位于索引字段上,请不要使用可调整的游标,而是使用常规游标。Keep track of the last value of the indexed field returned by the query. 跟踪查询返回的索引字段的最后一个值。To retrieve the newly added documents, query the collection again using the last value of the indexed field in the query criteria, as in the following example:要检索新添加的文档,请使用查询条件中索引字段的最后一个值再次查询集合,如下例所示:

db.<collection>.find( { indexedField: { $gt: <lastvalue> } } )

Consider the following behaviors related to tailable cursors:考虑以下与可裁剪游标相关的行为:

  • Tailable cursors do not use indexes and return documents in natural order.可尾随游标不使用索引,而是按自然顺序返回文档。
  • Because tailable cursors do not use indexes, the initial scan for the query may be expensive; but, after initially exhausting the cursor, subsequent retrievals of the newly added documents are inexpensive.因为可裁剪游标不使用索引,所以查询的初始扫描可能会很昂贵;但是,在最初耗尽游标之后,随后对新添加的文档的检索是廉价的。
  • Tailable cursors may become dead, or invalid, if either:如果出现以下情况之一,可跟踪游标可能会失效

    • the query returns no match.查询不返回匹配项。
    • the cursor returns the document at the "end" of the collection and then the application deletes that document.游标返回集合“末尾”的文档,然后应用程序删除该文档。

    A dead cursor has an ID of 0.失效游标的ID为0

See your driver documentation for the driver-specific method to specify the tailable cursor.有关指定可裁剪游标的驱动程序特定方法,请参阅驱动程序文档