How do you insert documents in MongoDB?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for MongoDB development. It reveals whether you understand the building blocks that more complex concepts rely on.

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().

Common Mistake

Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong MongoDB candidates.