How do you insert documents in MongoDB?

Answer

MongoDB provides several methods to insert documents into a collection: insertOne(): inserts a single document. db.users.insertOne({ name: "Alice", email: "alice@example.com", age: 30 }). Returns an acknowledgment with the inserted document's _id. If no _id is provided, MongoDB generates an ObjectId automatically. insertMany(): inserts multiple documents at once (more efficient than multiple insertOne calls). db.users.insertMany([ { name: "Bob", age: 25 }, { name: "Carol", age: 35 } ]). Options: ordered: false — continues inserting even if one document fails (e.g., duplicate key). Default is ordered: true (stops on first error). Insert behavior: if a document with the same _id already exists, insertOne/insertMany throws a duplicate key error; use replaceOne() or upsert to overwrite existing documents. Bulk write: db.collection.bulkWrite([]) — perform multiple operations (insert, update, delete) in a single command with configurable ordering. Validation: if schema validation is configured on the collection, inserted documents are validated against the rules. Auto-generated _id: ObjectId is unique across all machines and sortable by time — use it as a creation timestamp: new ObjectId().getTimestamp().