tamaslnagy
tamaslnagy

Reputation: 441

How to efficiently update the most recent document inserted into a MongoDB collection?

If I remember correctly the ObjectId of a MongoDB document contains the timestamp of its creation. What would be the best way to update only the most recent document in a collection?

So say that I have a bunch of game documents and every so often a new document is created and every score should be saved to the most recent game, not to the previous games. I would like to do this in order to not store the game object in memory.

Upvotes: 0

Views: 698

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

I've tried a couple of things and I couldn't make it in single operation. However, you don't need to store whole game object in memory. You can just ask for the latest _id. Something like this (shell pseudo syntax).

var last_id = db.games.find({}, {_id: 1}).sort({_id: -1}).limit(1);
db.games.update({_id: last_id}, {$inc: {score: 1}});

Update:

Okay, I should probably go to sleep now. Of course, it can be done using findAndModify. Here's JS code.

db.runCommand({findAndModify: 'games', 
               sort: {_id: -1}, 
               update: {$inc: {score: 1}}})

Upvotes: 2

Related Questions