insertOne and insertMany
Learners will insert single and bulk documents and inspect the auto-generated _id field returned by each operation.
The Two Insert Methods
MongoDB provides two methods for adding documents to a collection:
- insertOne(doc) — inserts a single document and returns an object with
acknowledgedandinsertedId - insertMany(docs) — inserts an array of documents and returns
acknowledgedandinsertedIds(an object mapping array index to generated _id)
Both methods are synchronous in mongosh and return Promises in Node.js driver code. Always await them in async Node.js functions to handle errors properly.
// insertOne
const res1 = await db.collection('users').insertOne({ name: 'Alice', age: 28 });
console.log(res1.insertedId); // ObjectId('...')
// insertMany
const res2 = await db.collection('users').insertMany([
{ name: 'Bob', age: 32 },
{ name: 'Carol', age: 25 }
]);
console.log(res2.insertedIds);
// { '0': ObjectId('...'), '1': ObjectId('...') }Auto-Generated ObjectId
When you insert a document without an _id field, MongoDB generates an ObjectId automatically. The ObjectId is a 12-byte BSON type whose structure ensures global uniqueness across distributed nodes without a central counter:
- Bytes 0-3: Unix timestamp (seconds) — allows approximate sort by insertion time
- Bytes 4-8: Random value (generated once per process)
- Bytes 9-11: Incrementing counter (initialized to a random value)
This design means two different servers inserting documents at the same millisecond will still produce different ObjectIds, making distributed inserts collision-free.
// Auto-generated ObjectId on insert
db.items.insertOne({ name: 'Widget' });
// { acknowledged: true, insertedId: ObjectId('64a2f3b1c9e7e12345678901') }
// Extract timestamp from an ObjectId
const id = ObjectId('64a2f3b1c9e7e12345678901');
print(id.getTimestamp());
// ISODate('2023-07-03T10:15:29.000Z')
// Sorting by _id gives approximate insertion order
db.items.find({}).sort({ _id: 1 });