Getlasterror command
When writing data to a database, MongoDB does not wait for a response message by default. Use the getlasterror command to ensure that the operation has been correctly executed.
In many drivers, the getlasterror command is automatically called when you use the "Security" mode (set write concern) for saving and updating. But when this special getlasterror command is called, what actually happens. Here, we will introduce how it works.
Run in shell
The getlasterror command checks the previous database operation error of this connection. Because it is a command, there are some methods to use it:
> db.$cmd.findOne({getlasterror:1})
Or in shell:
> db.runCommand("getlasterror")
Or use the shell ASSISTANT:
> db.getLastError()
In Mongo shell, DB. getlasterror () returns the last error-null if no error exists. Use dB. getlasterrorobj () to view the complete error results.
If no error occurs, DB. getlasterrobj (). Err should be empty.
When to use
Getlasterror is mainly useful for write operations (although it is also set after a command or query ). Write operations do not return results by default: This saves the client time to wait for a round-trip between the client and server during write operations. If someone needs a returned result, he can always call getlasterror.
If you write data for MongoDB on multiple connections, it is important to call getlasterror on a connection to confirm that the data has been submitted to the database. For example, if you write data to connection #1 and want these writes to be reflected in the read operation on connection #2, you can call getlasterror after writing to connection #1 to ensure this.
To maximize the speed, skip getlasterror (or "safe mode") for unimportant writes "). Use it when you need to confirm that the write operation is successful.
Option
Fsync
When mongod (-- nojournal) is not run using the log function, the synchronization option forces the database to return after synchronizing all files.
When mongod is run using the log function, the synchronization option is returned only after the next group is submitted.
> db.runCommand({getlasterror:1,fsync:true})
{ "err" : null, "n" : 0, "fsyncFiles" : 2, "ok" : 1 }
J
V2.0 +: When j: true is set, the getlasterror call will not be returned until the log is submitted. If the log feature is not enabled on the server, it returns immediately and succeeds.
> db.runCommand({getlasterror:1,j:true})
W
The client can be blocked until a write operation is copied to N servers.
Wtimeout can be used together with w. No timeout by default (permanent wait ).
> db.getLastError(2, 5000) // w=2, timeout 5000ms
Note that these options can be used together: it makes sense to wait for the log confirmation and write operation to reach the confirmation of most nodes in the replication group.
Logo and majority
Mongodb2.0 has the ability to control which nodes are written. Instead of setting the number of nodes that must be recognized for write operations, you can set a flag-based rule in the configuration.
In addition to the flag rules, you can also set a string "majority ":
>db.getLastError("majority") // waits for more than 50% of the configured nodes to acknowledge the
write (until replication is applied to the point of that write)
Return Value
The return value of this command is a multi-Field object. Common fields are already listed below; other fields may exist here.
- If OK-is true, the getLastError command is successfully completed. It does not mean that there was no error last time.
- Err-if it is not empty, an error occurs. The value is a description of the error body.
- Code-if it is set, it indicates the error code.
- ConnectionId-connection id.
- LastOp-op-id of the last operation
For updates:
- N-if an update is completed, it indicates the number of updated documents.
W: <n>/<tag>
- Wnote-if it is set, it indicates that some unusual things happen here, involving the use of w:
- Wtimeout-If timeout occurs, set this value to true.
- Waited-if the timeout time is reached, how long will the Mark wait, in milliseconds
- Wtime-the time spent waiting for the Operation to complete
Use getLastError in the driver
The driver supports the use of getLastError in command format, and many also provide the "safe" Mode for operations. For more information about the "safe" mode, see the driver documentation.
Mongo shell REPL Behavior
The database shell executes resetError ()-and prints errors automatically before each read/eval/print loop command calculation. If an error occurs during each calculation. Therefore, if you call db. getLastError () at the shell prompt after an error occurs, an empty result is returned. However, if you call it before the prompt is returned, the result is expected:
> try { db.foo.findOne() } catch(e) { print("preverr:" + tojson(db.getPrevError())); print("lasterr:"
+ tojson(db.getLastError()));}
preverr:{"err" : "unauthorized" , "nPrev" : 1 , "ok" : 1}
lasterr:"unauthorized"
GetPrevError command
When a large number of write operations are performed, resetError () and getPrevError () are efficient methods to check whether the operation is successful.
For example, if we want to insert 1000 objects to an integration, it will be very slow to return values after 1000 checks through the network. Instead, you can do something like this:
db.resetError();
for( loop 1000 times... )
db.foo.save(something...);
if( db.getPrevError().err )
print("didn't work!");
Index-related commands
Create an index
Ensureindex () is an assistant function used to create an index. Its execution will create an index by adding the index information to the collection system. indexes.
> use test
> db.myCollection.ensureIndex(<keypattern>);
> // same as:
> db.system.indexes.insert({ name: "name", ns: "namespaceToIndex",
key: <keypattern> });
Note: Once you insert an index, all subsequent inserted documents will be indexed, just like the existing documents in the collection. If you have a large set, it takes a lot of time and blocks other operations.
You can query system. Indexes in Foo in the database test to view all indexes:
>db.system.indexes.find( { ns: "test.foo" } );
In some drivers, ensureindex () remembers whether it was recently called and gave up the index insertion Operation in this case. Even if this is not the case, ensureindex () is a lightweight operation that can be called frequently to ensure the existence of this index.
Discard an index
From shell:
db.mycollection.dropIndex(<name_or_pattern>)
db.mycollection.dropIndexes()
// example:
t.dropIndex( { name : 1 } );
From a Driver (original command object format; many drivers have helper functions ):
{ deleteIndexes: <collection_name>, index: <index_name> }
// "*" for <index_name> will drop all indexes except _id
Re-Indexing
The re-Index Command re-creates all indexes in a set:
db.myCollection.reIndex()
// same as:
db.runCommand( { reIndex : 'myCollection' } )
This is usually not required. You may want to deduplicate the index. When your set changes significantly or the disk space occupied by the index is surprisingly large.
Indexes starting from version 1.8 are automatically compressed when they are updated.
Re-indexing is a blocking operation (the index was rebuilt the day before yesterday) and will be slow for large sets.
The repair DATABASE Command re-creates all indexes in the database.
Index namespace
Each index has its own namespace for btree storage segments. The namespace is:
<collectionnamespace>.$<indexname>
This is an internal namespace that cannot be directly queried.