CRUD
insertOne() and insertMany()
Writing documents, ordered versus unordered inserts, and what comes back.
Insert writes new documents. insertOne for a single record. insertMany for a batch. If you omit _id, MongoDB generates an ObjectId — the same default as in Fundamentals.
db.users.insertOne({
name: "Priya",
age: 26,
city: "Bangalore",
role: "developer",
skills: ["Node.js"],
isActive: true
}){
acknowledged: true,
insertedId: ObjectId("64a1b2c3d4e5f6a7b8c90002")
}db.orders.insertMany([
{ userId: ObjectId("64a1b2c3d4e5f6a7b8c90001"), amount: 4500, status: "completed" },
{ userId: ObjectId("64a1b2c3d4e5f6a7b8c90001"), amount: 1200, status: "pending" }
]){
acknowledged: true,
insertedIds: {
0: ObjectId("64a1b2c3d4e5f6a7b8c90011"),
1: ObjectId("64a1b2c3d4e5f6a7b8c90012")
}
}Ordered vs unordered
insertMany is ordered by default. If document 3 has a duplicate _id, 4 and 5 never run. Pass { ordered: false } when you want the rest to continue — bulk imports, not a money transfer.
const result = await users.insertOne({
name: "Priya",
city: "Bangalore",
isActive: true,
});
// result.insertedIdInterview question
What does insertOne return, and who creates _id?
It returns acknowledged and insertedId. If the document had no _id, the driver or the server generates an ObjectId. I do not send a second query just to learn the id — it is already in the result.
Interview question
When would you set ordered: false on insertMany?
When a failure in the middle should not block the rest — a bulk load of products, for example. I would not use it for a sequence of writes that must all happen or none.