insertOne takes one document, insertMany an array, and neither requires the collection or database to exist: both are created on the first successful write. If a document has no _id, the driver (not the server) generates the ObjectId, which is why the result hands you the key immediately.
db.books.createIndex({ isbn: 1 }, { unique: true });
const a = db.books.insertOne({ title: "Eloquent JavaScript", isbn: "978-1593279509" });
console.log("insertOne ->", a.acknowledged, a.insertedId.toString());
const r = db.books.insertMany([
{ title: "Designing Data-Intensive Applications", isbn: "978-1449373320" },
{ title: "Refactoring", isbn: "978-0134757599", year: 2018 }
]);
console.log("insertMany ->", Object.values(r.insertedIds).map(String).join(" "));insertOne -> true 6ab1ca2482a8f2baa472170f insertMany -> 6ab1ca2482a8f2baa4721710 6ab1ca2482a8f2baa4721711
Documents in a batch need not share a shape: only Refactoring carries a year. What is not legal is a second document with an isbn the unique index already holds:
const batch = [{ title: "Refactoring (dup)", isbn: "978-0134757599" },
{ title: "Clean Architecture", isbn: "978-0134494166" }];
try { db.books.insertMany(batch); } catch (e) { console.log(e.message); }
console.log("ordered ->", db.books.countDocuments());
try { db.books.insertMany(batch, { ordered: false }); }
catch (e) { console.log(e.result.insertedCount, "inserted,", e.writeErrors.length, "failed"); }
console.log("unordered ->", db.books.countDocuments());E11000 duplicate key error collection: bookshelf.books index: isbn_1 dup key: { isbn:
"978-0134757599" }
ordered -> 3
1 inserted, 1 failed
unordered -> 4Those counts are the lesson. The first call is ordered (the default): the server stops dead at the failing element, so Clean Architecture never arrives and the count does not move. The second passes ordered: false, the server keeps going, and the good document lands. Either way the call throws, so inspect e.result and e.writeErrors rather than trusting the exception alone. Unordered batches are also faster; use ordered: true only when a later document depends on an earlier one.