- Reference >
- JavaScript Methods >
- db.collection.save()
db.collection.save()¶
-
db.collection.save(document)¶ The
save()method updates an existing document or inserts a document depending on the parameter.The
save()method takes the following parameter:Parameters: - document –
Specify a document to save to the collection.
If the document does not contain an _id field, then the
save()method performs an insert with the specified fields in the document as well as an_idfield with a unique objectid value.If the document contains an
_idfield, then thesave()method performs anupsertquerying the collection on the_idfield:- If a document does not exist with the specified
_idvalue, thesave()method performs an insert with the specified fields in the document. - If a document exists with the specified
_idvalue, thesave()method performs an update, replacing all field in the existing record with the fields from the document.
- If a document does not exist with the specified
Consider the following examples of the
save()method:Pass to the
save()method a document without an_idfield, so that to insert the document into the collection and have MongoDB generate the unique_idas in the following:This operation inserts a new document into the
productscollection with theitemfield set tobook, theqtyfield set to40, and the_idfield set to a uniqueObjectId:Note
Most MongoDB driver clients will include the
_idfield and generate anObjectIdbefore sending the insert operation to MongoDB; however, if the client sends a document without an_idfield, themongodwill add the_idfield and generate theObjectId.Pass to the
save()method a document with an_idfield that holds a value that does not exist in the collection to insert the document with that value in the_idvalue into the collection, as in the following:This operation inserts a new document into the
productscollection with the_idfield set to100, theitemfield set towater, and the fieldqtyset to30:Note
Most MongoDB driver clients will include the
_idfield and generate anObjectIdbefore sending the insert operation to MongoDB; however, if the client sends a document without an_idfield, themongodwill add the_idfield and generate theObjectId.Pass to the
save()method a document with the_idfield set to a value in thecollectionto replace all fields and values of the matching document with the new fields and values, as in the following:This operation replaces the existing document with a value of
100in the_idfield. The updated document will resemble the following:
- document –