MongoDB v3.2
1. Method Definition
db.collection.insert( <document or array of documents>, { writeConcern: <document>, ordered: <boolean> } )
The first parameter can be a document or an array of documents, that is, insert can insert multiple pieces of data at the same time
The second parameter is a document, writeConcern indicates the response level of the database when the write operation is performed, and ordered is a boolean value. If true, the documents in the specified array are inserted in order. If an error occurs when one of the documents is inserted, it will be returned directly. , the remaining documents will not be processed; if false, the error will be ignored and the remaining documents will be inserted. Defaults to true.
In addition, when inserting a document into the collection, if the document does not exist, it will be automatically created. If the _id field is not specified in the inserted document, it will be automatically generated.
2. Return value
Insert a single document and return a WriteResult object; insert multiple documents and return a BulkWriteResult object.
Returns when the insertion is successful:
WriteResult({ "nInserted" : 1 })
nInserted indicates the number of inserts
If a write concern error occurs when inserting, a message similar to the following is returned:
WriteResult({ "nInserted" : 1, "writeConcernError" : { "code" : 64, "errmsg" : "waiting for replication timed out at shard-a" } })
Errors unrelated to write concern while inserting:
WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.foo.$_id_ dup key: { : 1.0 }" } })
3. Write Concern
Used to set the response level of write operations
{ w: <value>, j: <boolean>, wtimeout: <number> }
w=0: The write operation does not wait for the server to respond to confirmation, even if the write fails, it will not respond. But can perceive network errors.
w=1: The response information of the single node or the master node in the cluster can be obtained. This value is the default value.
w=majority: The response information of multiple nodes (voting) in the cluster including the master node can be obtained, and this write operation will ensure that the disk journal is recorded, and the data will not be lost even if the power is turned off.
w>1: Yes Obtain the response information of multiple nodes including the master node, but the specified number must be consistent with the number of clusters, otherwise the operation will wait all the time, unless wtimeout
j=true is set: waiting for the operation to be written to the journal log will return the response, which can be tolerated Server down. The journaling parameter needs to be added when mongod is started to ensure that it can be used.
wtimeout: The timeout duration of the write operation, in milliseconds, and an error message will be returned if the timeout expires.