Tailable Cursors

By default, MongoDB will automatically close a cursor when the clienthas exhausted all results in the cursor. However, for cappedcollections you may use a TailableCursor that remains open after the client exhausts the results in theinitial cursor. Tailable cursors are conceptually equivalent to thetail Unix command with the -f option (i.e. with “follow”mode). After clients insert new additional documents into a cappedcollection, the tailable cursor will continue to retrievedocuments.

Use tailable cursors on capped collections that have high writevolumes where indexes aren’t practical. For instance,MongoDB replication uses tailable cursors totail the primary’s oplog.

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 ofthe indexed field returned by the query. To retrieve the newlyadded documents, query the collection again using the last value ofthe indexed field in the query criteria, as in the followingexample:

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

Consider the following behaviors related to tailable cursors:

  • Tailable cursors do not use indexes and return documents innatural order.

  • Because tailable cursors do not use indexes, the initial scan for thequery 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 andthen the application deletes that document.A dead cursor has an id of 0.

See your driver documentation for thedriver-specific method to specify the tailable cursor.