Justin Dearing
Justin Dearing

Reputation: 14948

Safe write from the mongodb shell

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.

Upvotes: 3

Views: 844

Answers (1)

Thilo
Thilo

Reputation: 262554

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).

Upvotes: 3

Related Questions