Inserting Documents into MongoDB using Node.js

Learn how to insert data into MongoDB collections using Node.js. This tutorial provides a clear guide with practical examples demonstrating how to use the `insertOne()` method for single document insertion and handle potential errors effectively.



Inserting Documents into MongoDB Using Node.js

This tutorial shows how to insert documents (records) into a MongoDB collection using Node.js. MongoDB is a NoSQL, document-oriented database. Node.js provides drivers to interact with MongoDB.

Inserting a Single Document

To insert a single document, use the `insertOne()` method. The first argument is the document (an object) you want to insert.


db.collection('collectionName').insertOne(document, callback);

The callback function is executed after the insertion; it handles potential errors.

Example: Inserting a single employee record:


var MongoClient = require('mongodb').MongoClient;
// ... (database connection code) ...
var myobj = { name: "John Doe", age: 30, city: "New York" };
db.collection('employees').insertOne(myobj, function(err, res) {
  if (err) throw err;
  console.log("1 record inserted");
  db.close();
});

Inserting Multiple Documents

Use the `insertMany()` method to insert multiple documents at once. The argument is an array of documents:


db.collection('collectionName').insertMany(documents, callback);

The callback includes the number of inserted documents (`res.insertedCount`).

Example: Inserting multiple customer records:


var MongoClient = require('mongodb').MongoClient;
// ... (database connection code) ...
var myobj = [
  { name: "Alice", age: 25, city: "London" },
  { name: "Bob", age: 30, city: "Paris" },
  // ... more documents
];
db.collection('customers').insertMany(myobj, function(err, res) {
  if (err) throw err;
  console.log("Number of records inserted: " + res.insertedCount);
  db.close();
});