CRUD: Create
CRUD stands for Create, Read, Update, Delete—the four fundamental operations for working with data in any database. In this chapter, we focus on Create: adding new documents to your MongoDB collections.
Understanding Document Insertion
Unlike relational databases where you must define a table schema before inserting data, MongoDB is schema-flexible. You can insert documents with different structures into the same collection. While this offers flexibility, it also means you should think carefully about your data model.
What Happens During Insert
When you insert a document:
- MongoDB validates the document structure (if validation rules exist)
- An
_id field is automatically generated if not provided
- The document is written to the collection
- If the collection doesn’t exist, MongoDB creates it automatically
The _id Field
Every document in MongoDB must have a unique _id field that acts as the primary key:
- If you don’t provide one, MongoDB generates an ObjectId
- ObjectIds are 12-byte unique identifiers (timestamp + machine + process + counter)
- You can provide your own
_id (string, number, etc.), but it must be unique
Letting MongoDB generate _id values is usually the best choice—ObjectIds are designed to be unique across distributed systems without coordination.
Insert Methods
Create operations add new documents to a collection. If the collection does not currently exist, insert operations will create the collection.
insertOne()
Inserts a single document into a collection.
db.users.insertOne({
name: "Alice",
age: 25,
status: "active"
})
Output:
{
"acknowledged": true,
"insertedId": ObjectId("60d5ec...")
}
insertMany()
Inserts multiple documents into a collection. Pass an array of documents.
db.users.insertMany([
{ name: "Bob", age: 30, status: "inactive" },
{ name: "Charlie", age: 35, status: "active" }
])
Output:
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("..."),
"1": ObjectId("...")
}
}
Ordered vs Unordered Inserts
By default, insertMany is ordered. If an error occurs during the insertion of one of the documents (e.g., duplicate key error), MongoDB stops inserting the remaining documents.
To allow the remaining documents to be inserted even if one fails, set ordered: false.
db.users.insertMany([
{ _id: 1, name: "A" },
{ _id: 1, name: "B" }, // Duplicate ID error
{ _id: 2, name: "C" }
], { ordered: false })
In this case, “A” and “C” will be inserted, and “B” will fail.
Summary
- Use
insertOne() for single documents.
- Use
insertMany() for multiple documents.
- MongoDB automatically adds an
_id if you don’t provide one.
insertMany is ordered by default; use { ordered: false } to continue on error.