Inserting Documents into a Collection
MongoDB stores data as BSON documents grouped into collections, and collections live inside a database. Unlike a relational table, a collection does not require a predefined schema, so calling insertOne() or insertMany() against a collection that does not yet exist creates it automatically, along with the parent database if needed.
Cricket analogy: It is like a scorebook that does not exist until the first ball is bowled — the moment Rohit Sharma faces the opening delivery of a match, the scorebook springs into existence and starts recording entries.
insertOne() and the _id Field
db.collection.insertOne(doc) inserts a single document and returns a result object containing acknowledged and insertedId. If the document you pass does not include an _id field, the MongoDB driver generates a 12-byte ObjectId client-side before sending the write, guaranteeing every document has a unique primary key without a round trip to the server.
Cricket analogy: It is like the scorer automatically stamping a unique delivery number on every ball bowled by Jasprit Bumrah, even if the umpire never explicitly calls one out — the numbering happens by default.
Bulk Insertion with insertMany()
db.collection.insertMany(docsArray, options) inserts an array of documents in a single call and returns insertedIds as a map of array index to generated ObjectId. By default the operation is ordered, meaning MongoDB inserts documents in array order and stops at the first error; passing { ordered: false } lets MongoDB attempt every document and continue past individual failures, which is faster for independent, unrelated writes.
Cricket analogy: It is like sending a whole squad list to the scorer at once before a match rather than announcing players one by one — an ordered team sheet stops the moment one name is invalid, while an unordered submission just skips the bad entry and registers the rest.
// Insert a single document
db.products.insertOne({
name: "Wireless Mouse",
price: 24.99,
tags: ["electronics", "accessories"],
inStock: true
});
// Insert many documents, continuing past errors
db.products.insertMany(
[
{ name: "USB-C Cable", price: 9.99, inStock: true },
{ name: "Laptop Stand", price: 34.5, inStock: false },
{ _id: 1001, name: "Keyboard", price: 49.0, inStock: true }
],
{ ordered: false }
);Both insertOne() and insertMany() are atomic at the single-document level: a document is either fully written or not written at all. There is no partial document write, even though insertMany() as a whole can partially succeed when { ordered: false } is used.
Schema Flexibility and Optional Validation
Because MongoDB collections are schema-less by default, two documents in the same products collection can have entirely different fields — one might include a warrantyMonths field while another does not. Teams that want structure can still enforce it by attaching a $jsonSchema validator to the collection with db.createCollection() or collMod, which rejects inserts that violate required fields or types.
Cricket analogy: It is like a squad where one player's profile lists bowling figures and another lists only batting stats — MongoDB allows that mixed profile sheet, but a team could still mandate that every player record include a jersey number field.
Inserting a document whose _id duplicates an existing one raises a E11000 duplicate key error, since _id is always uniquely indexed. In an ordered insertMany(), this error stops all subsequent inserts in the batch; documents before the failure remain committed, but none after it are attempted.
- insertOne() adds a single document; insertMany() adds an array of documents in one call.
- MongoDB auto-generates a 12-byte ObjectId for _id if you don't supply one yourself.
- insertMany() is ordered by default, stopping at the first error unless { ordered: false } is passed.
- Collections and databases are created implicitly on the first successful insert.
- Documents in the same collection can have different fields since MongoDB is schema-less by default.
- A $jsonSchema validator can be attached to a collection to enforce structure on future inserts.
- Duplicate _id values always raise an E11000 error because _id is uniquely indexed.
Practice what you learned
1. What does MongoDB do if you call insertOne() without providing an _id field?
2. By default, what happens when insertMany() encounters an error on the third document out of five?
3. How can you make insertMany() continue inserting valid documents even after one fails?
4. What error code appears when you try to insert a document with an _id that already exists in the collection?
5. What happens to a collection that does not yet exist when you call insertOne() against it?
Was this page helpful?
You May Also Like
Querying Documents
Learn how to retrieve documents from MongoDB collections using find() and findOne(), filters, projections, and cursor methods.
Updating Documents
Learn how to modify existing documents using updateOne, updateMany, replaceOne, update operators like $set and $inc, and upserts.
Deleting Documents
Learn how to remove documents from MongoDB collections with deleteOne and deleteMany, and how to safely drop entire collections.