问题
I'm writing a long-polling script to check for new documents in my mongo collection and the only way I know of checking to see whether or not changes have been made in the past iteration of my loop is to do a query getting the last document's ID and parsing out the timestamp in that ID and seeing if it's greater than the timestamp left since I last made a request.
Is there some kind of approach that doesn't involve making a query every time or something that makes that query the fastest?
I was thinking a query like this:
db.chat.find().sort({_id:-1}).limit(1);
But it would be using the PHP driver.
回答1:
The fastest way will be creating indexes on timestamp
field.
Creating index:
db.posts.ensureIndex( { timestamp : 1 } )
Optimizes this query:
db.posts.find().sort( { timestamp : -1 } )
findOne
give you only one the last timestamp.
nice to help you.
回答2:
@Zagorulkin Your suggestion is surely going to help in the required scenario. However i don't think so sort() works with findOne().
来源:https://stackoverflow.com/questions/14332101/what-is-the-fastest-way-to-see-when-the-last-update-to-mongodb-was-made