– Query the capped collection and return a tailable cursor that blocks for several seconds waiting for new documents 

auto_ptr<DBClientCursor> c = conn.query(ns, query, 0, 0, 0, QueryOption_CursorTailable | QueryOption_AwaitData ); 

* Specify the capped collection using ns as an argument to the function. 

* Set the QueryOption_CursorTailable option to create a tailable cursor. 

* Set the QueryOption_AwaitData option so that the returned cursor blocks for a few seconds to wait for data. 

– In an inner while (1) loop, read the documents from the cursor: 

* If the cursor has no more documents and is not invalid, loop the inner while loop to recheck for more documents. 

* If the cursor has no more documents and is dead, break the inner while loop. 

* If the cursor has documents: 

· output the document, 

· update the lastValue value, 

· and loop the inner while (1) loop to recheck for more documents. 

– If the logic breaks out of the inner while (1) loop and the cursor is invalid: 

* Use the lastValue value to create a new query condition that matches documents added after the lastValue . Explicitly ensure $natural order with the hint() method: 

query = QUERY( "insertDate" << GT << lastValue ).hint( BSON( "$natural" << 1 ) ); 

* Loop through the outer while (1) loop to re-query with the new query condition and repeat. 

## See also: 

Detailed blog post on tailable cursor 15 

## 3.3.12 Create an Auto-Incrementing Sequence Field 

## Synopsis 

MongoDB reserves the _id field in the top level of all documents as a primary key. _id must be unique, and always has an index with a unique constraint (page 504). However, except for the unique constraint you can use any value for the _id field in your collections. This tutorial describes two methods for creating an incrementing sequence number for the _id field using the following: 

• Use Counters Collection (page 126) 

• Optimistic Loop (page 127) 

