This chapter introduces how to insert document data into MongoDB using the mongo shell.

Inserting a Single Document

The db.collection.insertOne() method is used to insert a single document into a collection.

If the document does not specify the _id field, MongoDB will automatically generate a unique ObjectId for the _id field.

Note: ObjectId is a built-in unique ID generator in MongoDB used for ID generation.

Example: Insert a document into the inventory collection:

db.inventory.insertOne(
   { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)

Returns:

{
	"acknowledged" : true,
	"insertedId" : ObjectId("609bf11dfc901345cafc438a")
}

If the insertion is successful, it returns the primary key. The insertedId field is the automatically generated unique ID by MongoDB. If the inventory collection does not exist, it is automatically created.

Query the inserted document data:

> db.inventory.find( { item: "canvas" } )
{ "_id" : ObjectId("609bf11dfc901345cafc438a"), "item" : "canvas", "qty" : 100, "tags" : [ "cotton" ], "size" : { "h" : 28, "w" : 35.5, "uom" : "cm" } }

Using the find method, input the query condition to find the document data where item is "canvas".

Inserting Multiple Documents

The db.collection.insertMany() method can insert multiple documents into a collection.

Example: Insert three document data by passing an array to the insertMany method:

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" } }
])

Return value:

{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("609bf30ffc901345cafc438b"),
		ObjectId("609bf30ffc901345cafc438c"),
		ObjectId("609bf30ffc901345cafc438d")
	]
}

Returns the IDs of the newly inserted three documents.

Insertion Behavior

Collection Creation

In MongoDB, there is no need to create a collection in advance. When inserting data for the first time, if the collection does not exist, it is automatically created.

_id Field

In MongoDB, every document stored in a collection has a unique _id field acting as the primary key. If the inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

Atomicity

All write operations in MongoDB are atomic operations at the single document level.