Inserting documents into MongoDB collections from Node.js applications is executed using insertOne() for single documents and insertMany() for bulk dataset insertions.
flowchart LR
A["Document Object: { name: 'Alice' }"] --> B["insertOne() invocation"]
B --> C["Node.js Driver Generates 12-byte BSON ObjectId"]
C --> D["Document Saved with _id: ObjectId('65c1f...')"]
import { MongoClient, ObjectId } from 'mongodb';
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);
async function executeDocumentInserts() {
try {
await client.connect();
const db = client.db('kodersolution_no_sql');
const products = db.collection('products');
// 1. Insert Single Document
const singleDoc = {
title: 'Wireless Mechanical Keyboard',
category: 'Electronics',
price: 129.99,
tags: ['gadgets', 'hardware'],
createdAt: new Date()
};
const insertOneResult = await products.insertOne(singleDoc);
console.log(`Single Insert Success! Document _id: ${insertOneResult.insertedId}`);
// 2. Insert Multiple Documents (Bulk Insert)
const bulkDocs = [
{ title: 'Ergonomic Mouse', price: 59.99, category: 'Electronics' },
{ title: '4K USB-C Monitor', price: 399.99, category: 'Electronics' },
{ title: 'Standing Desk Converter', price: 219.00, category: 'Furniture' }
];
const insertManyResult = await products.insertMany(bulkDocs);
console.log(`Bulk Insert Success! Inserted ${insertManyResult.insertedCount} documents.`);
} catch (err) {
console.error('MongoDB Insert Error:', err.message);
} finally {
await client.close();
}
}
executeDocumentInserts();
_id Generation: If an inserted document does not contain an _id field, the driver generates a unique 12-byte BSON ObjectId automatically.{ ordered: false } on Bulk Inserts: Pass { ordered: false } to insertMany() so remaining valid documents are still inserted even if one document fails validation._id: Never attempt to modify the _id field of an existing document once created.What property returned by insertOne() contains the newly generated unique document identifier?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.