Biggie
Biggie

Reputation: 7067

MongoDB-upsert: fire and forget

I know that MongoDB uses async writes by default when inserting/updating/deleting documents. My question is if these updates are still performed in order.

Let's assume the following upsert-queries followed by a delete-query:

db.servers.update({ "server": "abcdef" }, { "$set": { "lastSeen": new Date()}}, /*upsert=*/ true);
db.servers.update({ "server": "uvwxyz" }, { "$set": { "lastSeen": new Date()}}, /*upsert=*/ true);
db.servers.remove({ "lastSeen": { "$lt": new Date(Date.now() - 3600000) }  });

If these comands are executed in these order, is then guaranteed (if the operations succeeds) that first the two documents are inserted/updated and then the delete operation will delete outdated documents? I want that the both inserted/deleted documents are not deleted because their "lastSeen"-value was updated.

I think the "async-write-thing" has only to do with the time at which data is written from RAM to Disc. I think it does not affect the order of the commands so that the example above will always work (if the updates succeed), right?

EDIT: I use a single mongod-instance. No replica-set, no sharding :-)

Upvotes: 1

Views: 919

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230521

Commands sent via single connection are serialized. So, if you do send those through one connection, it's guaranteed that remove will happen after the two inserts.

Async writes (AKA "fire and forget") means that client library doesn't wait for acknowledgement of the write. It just spits the insert into the socket and forgets about it. If, when applying this insert, there's a unique index violation (for example), you'll never know.

By the way, you can use mongodb's latest feature: TTL indexes! MongoDB will delete stale data on its own, you just keep inserting :)

Upvotes: 3

Related Questions