Inserting Documents
Add new documents to a collection using insertOne and insertMany.
insertOne
insertOne() adds a single document to a collection.
db.users.insertOne({ name: "Ada Lovelace", email: "ada@example.com", age: 28,});Click Run to see what this code prints.
insertMany
insertMany() adds multiple documents in a single operation, more efficient than calling insertOne() repeatedly.
db.users.insertMany([ { name: "Grace Hopper", age: 34 }, { name: "Alan Turing", age: 29 }, { name: "Katherine Johnson", age: 41 },]);By default, insertMany() stops at the first error, leaving earlier documents inserted. Pass { ordered: false } to continue inserting the remaining documents even if one fails.
Understanding the Result
Both operations return an object confirming success and listing the auto-generated _id value(s) — useful for immediately referencing the newly created document elsewhere in your application logic.
Common Beginner Mistakes
By default (ordered: true), a failure partway through still leaves earlier documents inserted — it isn't all-or-nothing unless wrapped in a transaction.
Let MongoDB generate the ObjectId automatically unless you have a specific, well-understood reason to supply your own.
FAQs
Practically yes, bound by the 48MB maximum BSON message size — for very large bulk inserts, batch them into smaller chunks.
Nothing special — that field simply doesn't exist on this document; querying for it will treat it as undefined/absent, not an error.
Summary
insertOne and insertMany cover single and bulk document creation, both returning the generated _id values. Next, you'll learn to read data back out with find().