Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polling MongoDb on Indexed Field vs Tailable Cursor

Tags:

mongodb

In MongoDb's documentation about tailable cursors it states the following:

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

I'm setting up a query to find all documents after a specific point in time, and then to keep returning documents as they are inserted. I imagine the easiest way of doing this is to query on the _id (provided we're using ObjectIds, which we are) for anything $gt the time I want.

Since _id is indexed by default, how bad is it to continually poll MongoDb with the last _id I got and keep asking for things $gt it? I realize that this would only be within 1 second precision or so, since ObjectIds only store seconds since epoch, but I can live with that, so I assume I'd be querying at least once per second.

I guess I'm just surprised that the documentation recommends the approach of querying (presumably, continually in my case) versus keeping a tailable cursor open: I would have thought that push would be cheaper than pull?

like image 856
FreeMemory Avatar asked Mar 07 '17 07:03

FreeMemory


People also ask

What is a Tailable cursor in MongoDB?

Give Feedback. By default, MongoDB will automatically close a cursor when the client has exhausted all results in the cursor. However, for capped collections you may use a Tailable Cursor that remains open after the client exhausts the results in the initial cursor.

What are capped collections in MongoDB?

What Is a Capped Collection in MongoDB? Fixed-size collections are called capped collections in MongoDB. While creating a collection, the user must specify the collection's maximum size in bytes and the maximum number of documents that it would store.


1 Answers

There's a big caveat here that I think that you might have overlooked. Tailable cursors only work for capped collections. Using a capped collection is probably not a general purpose solution, it's going to require careful planning to ensure that you size the capped collection appropriately to account for your data size and growth.

like image 187
helmy Avatar answered Nov 01 '22 20:11

helmy