- MongoDB CRUD Operations >
- MongoDB CRUD Tutorials >
- Insert Documents
Insert Documents¶
On this page
In MongoDB, the db.collection.insert()
method adds new
documents into a collection. In addition, both the
db.collection.update()
method and the
db.collection.save()
method can also add new documents
through an operation called an upsert. An upsert is an operation
that performs either an update of an existing document or an insert of
a new document if the document to modify does not exist.
This tutorial provides examples of insert operations using each of the
three methods in the mongo
shell.
Insert a Document with insert()
Method¶
The following statement inserts a document with three fields into the
collection inventory
:
In the example, the document has a user-specified _id
field value
of 10
. The value must be unique within the inventory
collection.
For more examples, see insert()
.
Insert a Document with update()
Method¶
Call the update()
method with the upsert
flag to create a new document if no document matches the update’s
query criteria. [1]
The following example creates a new document if no document in the
inventory
collection contains { type: "books", item : "journal"
}
:
MongoDB adds the _id
field and assigns as its value a unique
ObjectId. The new document includes the item
and type
fields
from the <query>
criteria and the qty
field from the
<update>
parameter.
For more examples, see update()
.
[1] | Prior to version 2.2, in the mongo shell, you would specify
the upsert and the multi options in the
update() method as positional boolean options.
See update() for details. |
Insert a Document with save()
Method¶
To insert a document with the save()
method,
pass the method a document that does not contain the _id
field or a
document that contains an _id
field that does not exist in the
collection.
The following example creates a new document in the inventory
collection:
MongoDB adds the _id
field and assigns as its value a unique
ObjectId.
For more examples, see save()
.