MongoDB Insert
MongoDB writes new documents with insertOne() for a single record or insertMany() for a batch, both returning identifiers for whatever was stored.
Inserting a Single Document
db.collection.insertOne(document) writes exactly one document to a collection, creating the collection first if it doesn't already exist. It returns a result object containing acknowledged: true and an insertedId, which is either the _id you supplied or the ObjectId MongoDB generated for you.
Inserting Many Documents at Once
db.collection.insertMany(documentsArray) writes an array of documents in a single call, which is far more efficient than looping over insertOne(). By default the inserts are ordered, meaning MongoDB stops at the first error; passing { ordered: false } tells it to attempt every document and report all failures together.
Handling Duplicate Keys and Errors
- Every document's _id must be unique within its collection
- Inserting a duplicate _id raises a duplicate key error (E11000)
- Ordered inserts (the default) stop at the first failed document
- Unordered inserts ({ ordered: false }) skip failures and keep going
- Each document is written atomically, but a multi-document insertMany() as a whole is not
Insert one document
db.products.insertOne({
name: "Wireless Mouse",
price: 24.99,
inStock: true
})Insert many documents
db.products.insertMany([
{ name: "Keyboard", price: 49.99 },
{ name: "Monitor Stand", price: 19.5 },
{ name: "USB Hub", price: 15.0 }
])Insert many, ignoring failures
db.products.insertMany(
[
{ _id: 1, name: "Webcam" },
{ _id: 1, name: "Duplicate ID" },
{ _id: 2, name: "Headset" }
],
{ ordered: false }
)Exercise: MongoDB Insert
What does MongoDB do if you call insertOne() without an _id field?