Node.js Tutorial
- Node.js Tutorial
- Install Node.js on Windows
- Install Node.js on Linux/Ubuntu/CentOS
- Node.js First Example
- Node.js Console
- Node.js REPL
- Node.js Package Manager
- Node.js Command Line Options
- Node.js Global Objects
- Node.js OS
- Node.js Timer
- Node.js Errors
- Node.js DNS
- Node.js Net
- Node.js Crypto
- Node.js TLS/SSL
- Node.js Debugger
- Node.js Process
- Node.js Child Process
- Node.js Buffers
- Node.js Streams
- Node.js File System (FS)
- Node.js Path
- Node.js StringDecoder
- Node.js Query String
- Node.js ZLIB
- Node.js Assertion Testing
- Node.js V8
- Node.js Callbacks
- Node.js Events
- Node.js Punycode
- Node.js TTY
- Node.js Web Module
- NestJS
Node.js MySQL
Node.js MongoDB
Nodejs Difference
Node.js MCQ
Node.js Express
Nodejs Interview Questions
Node.js MongoDB Insert Record
The insertOne method is used to insert record in MongoDB's collection. The first argument of the insertOne method is an object which contains the name and value of each field in the record you want to insert.
Example
(Insert Single record)
Insert a record in "employees" collection.
Advertisement
Create a js file named "insert.js", having the following code:
- var MongoClient = require('mongodb').MongoClient;
- var url = "mongodb://localhost:27017/ MongoDatabase";
- MongoClient.connect(url, function(err, db) {
- if (err) throw err;
- var myobj = { name: "Ajeet Kumar", age: "28", address: "Delhi" };
- db.collection("employees").insertOne(myobj, function(err, res) {
- if (err) throw err;
- console.log("1 record inserted");
- db.close();
- });
- });
Open the command terminal and run the following command:
- Node insert.js
Now a record is inserted in the collection.
Insert Multiple Records
You can insert multiple records in a collection by using insert() method. The insert() method uses array of objects which contain the data you want to insert.
Example
Insert multiple records in the collection named "employees".
Create a js file name insertall.js, having the following code:
- var MongoClient = require('mongodb').MongoClient;
- var url = "mongodb://localhost:27017/ MongoDatabase";
- MongoClient.connect(url, function(err, db) {
- if (err) throw err;
- var myobj = [
- { name: "Mahesh Sharma", age: "25", address: "Ghaziabad"},
- { name: "Tom Moody", age: "31", address: "CA"},
- { name: "Zahira Wasim", age: "19", address: "Islamabad"},
- { name: "Juck Ross", age: "45", address: "London"}
- ];
- db.collection("customers").insert(myobj, function(err, res) {
- if (err) throw err;
- console.log("Number of records inserted: " + res.insertedCount);
- db.close();
- });
- });
Open the command terminal and run the following command:
- Node insertall.js
You can see here 4 records are inserted.