- 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_id
field with a unique objectid value.If the document contains an
_id
field, then thesave()
method performs anupsert
querying the collection on the_id
field:- If a document does not exist with the specified
_id
value, thesave()
method performs an insert with the specified fields in the document. - If a document exists with the specified
_id
value, 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_id
field, so that to insert the document into the collection and have MongoDB generate the unique_id
as in the following:This operation inserts a new document into the
products
collection with theitem
field set tobook
, theqty
field set to40
, and the_id
field set to a uniqueObjectId
:Note
Most MongoDB driver clients will include the
_id
field and generate anObjectId
before sending the insert operation to MongoDB; however, if the client sends a document without an_id
field, themongod
will add the_id
field and generate theObjectId
.Pass to the
save()
method a document with an_id
field that holds a value that does not exist in the collection to insert the document with that value in the_id
value into the collection, as in the following:This operation inserts a new document into the
products
collection with the_id
field set to100
, theitem
field set towater
, and the fieldqty
set to30
:Note
Most MongoDB driver clients will include the
_id
field and generate anObjectId
before sending the insert operation to MongoDB; however, if the client sends a document without an_id
field, themongod
will add the_id
field and generate theObjectId
.Pass to the
save()
method a document with the_id
field set to a value in thecollection
to 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
100
in the_id
field. The updated document will resemble the following:
- document –