tags:

views:

36

answers:

1

How do I do a "safe" write that flushes to disk immediately from javascript? I'd like to be able to do this from both the shell and a stored javascript "CRUD" procedure. Is it just a matter of:

db.foo.insert({stuff: "yes", meta: "physics"});
db.runCommand( "getlasterror" ) ;

The wiki is unclear on this.

+2  A: 

Yes, you would be using the Last Error command, but you need to set the fsync flag (and/or the replication parameter, depending on your definition of "safe"):

# force fsync
> db.runCommand({getlasterror:1,fsync:true})

# wait for replication to one other server (w = 2)
> db.runCommand( { getlasterror : 1 , w : 2 } )

If you are doing more than one write, you can ask for fsync or replication after the last one. This will make all previous writes "safe" as well (since they are applied in order). You do not have to pay the cost for every write (unless you need them to be safe individually, not just as a set).

Thilo
Thilo, I have no shards, no replica sets, no nothing other than once a day backups, which I do test. So safe is "write to this server."I know that "single server durability" is coming in 1.8, but I'm actually not really sure what that means.
Justin Dearing
Single server durability would mean that you do not risk losing data between fsync. It probably also means faster database recovery (now you only lose one minute of data, but the database repair may take a lot of time before you are back online). In traditional databases (like Oracle) this is implemented using a redo log: even though you do not sync the whole database to disk on every commit, you still write enough log information to be able to reconstruct what is missing. Not sure if that is the approach that is planned for 1.8, though.
Thilo
Single server durability still requires that you have no disk crashes (it only protects against power outages and such). If you lose the disk, and have no replication (or a RAID), you lose all the data since your last external backup.
Thilo