Q1. How do you insert a single document in MongoDB?
Use the insertOne() method on a collection. Example:
db.users.insertOne({
name: "John",
age: 30,
email: "john@example.com"
})
This returns an object containing the inserted document's _id. If _id is not provided, MongoDB generates a unique ObjectId automatically.Q2. How do you insert multiple documents at once?
Use insertMany() with an array of documents:
db.users.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 28 },
{ name: "Charlie", age: 32 }
])
By default, if one document fails, the rest are still inserted (ordered: false). You can set ordered: true to stop on first error.Q3. What happens if you don't provide an _id field?
MongoDB automatically generates a unique ObjectId for the _id field. The ObjectId is a 12-byte value consisting of a timestamp, machine identifier, process ID, and counter. This ensures uniqueness across the cluster. You can also provide your own _id, but it must be unique within the collection.
Q4. How do you insert documents with arrays and embedded objects?
MongoDB documents can contain nested structures:
db.products.insertOne({
name: "Laptop",
specs: {
ram: "16GB",
storage: "512GB SSD"
},
tags: ["electronics", "computers"]
})
There's no limit on nesting depth, but documents have a size limit of 16MB.Q5. What is the difference between insert and save methods?
The save() method is deprecated in modern MongoDB drivers. It would insert if _id didn't exist, or update if it did. insertOne() and insertMany() are the recommended methods. They provide clearer semantics and better performance. Always use insertOne() for single inserts and insertMany() for bulk inserts.
