getLastError

Definition

getLastError

The getLastError command returns the error status of the last operation on the current connection. By default MongoDB does not provide a response to confirm the success or failure of a write operation, clients typically use getLastError in combination with write operations to ensure that the write succeeds.

Consider the following prototype form.

{ getLastError: 1 }

The following options are available:

Parameters:
  • j (boolean) –

    If true, wait for the next journal commit before returning, rather than a full disk flush. If mongod does not have journaling enabled, this option has no effect.

    If you specify j for a write operation, mongod will wait no more than 1/3 of the current journalCommitInterval before writing data to the journal.

  • w – When running with replication, this is the number of servers to replicate to before returning. A w value of 1 indicates the primary only. A w value of 2 includes the primary and at least one secondary, etc. In place of a number, you may also set w to majority to indicate that the command should wait until the latest write propagates to a majority of replica set members. If using w, you should also use wtimeout. Specifying a value for w without also providing a wtimeout may cause getLastError to block indefinitely.
  • fsync (boolean) – If true, wait for mongod to write this data to disk before returning. Defaults to false. In most cases, use the j option to ensure durability and consistency of the data set.
  • wtimeout (integer) – Optional. Milliseconds. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, the getLastError command will return with an error status.

Examples

Confirm Replication to Two Replica Set Members

The following example ensures the operation has replicated to two members (the primary and one other member):

db.runCommand( { getLastError: 1, w: 2 } )

Confirm Replication to a Majority of a Replica Set

The following example ensures the write operation has replicated to a majority of the configured members of the set.

db.runCommand( { getLastError: 1, w: "majority" } )

Set a Timeout for a getLastError Response

Unless you specify a timeout, a getLastError command may block forever if MongoDB cannot satisfy the requested write concern. To specify a timeout of 5000 milliseconds, use an invocation that resembles the following:

db.runCommand( { getLastError: 1, w: 2, wtimeout:5000 } )