- MongoDB CRUD Operations >
- Insert Documents
Insert Documents¶
This page provides examples of insert operations in the
mongo shell.
Creating a Collection
If the collection does not currently exist, insert operations will create the collection.
Insert a Document via db.collection.insertOne()¶
New in version 3.2.
db.collection.insertOne() inserts a single document into a collection.
The following example inserts a new document into the inventory
collection. Since the document does not specify an _id field,
MongoDB adds the _id field with an ObjectId value to the new
document. See Insert Behavior.
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
You can run this method in the web shell below:
insertOne() will return a document that
includes the newly inserted document’s _id field value. For an example of
a return document, see db.collection.insertOne() reference.
To retrieve the document that you just inserted, query the collection:
db.inventory.find( { item: "canvas" } )
For more information and examples, see
db.collection.insertOne().
Insert Multiple Documents via db.collection.insertMany()¶
New in version 3.2.
db.collection.insertMany() can insert multiple
documents into a collection. Pass an
array of documents to the method.
The following example inserts three new documents into the inventory
collection. Since the documents do not specify an _id field,
MongoDB adds the _id field with an ObjectId value to each document.
See Insert Behavior.
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])
You can run this method in the web shell below:
insertMany() will return a document that
includes the newly inserted documents _id field values. See the
reference for an example.
To retrieve the inserted documents, query the collection:
db.inventory.find()
For more information and examples, see
db.collection.insertMany().
Insert Behavior¶
Collection Creation¶
If the collection does not currently exist, insert operations will create the collection.
_id Field¶
In MongoDB, each document stored in a collection requires a unique
_id field that acts as a primary key. If an inserted
document omits the _id field, the MongoDB driver automatically
generates an ObjectId for the _id field.
This also applies to documents inserted through update operations with upsert: true.
Atomicity¶
All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions
Write Acknowledgement¶
With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.