Nodejs MongoDB Insert Record

In this tutorial you will learn about the Nodejs MongoDB Insert Record and its application with practical example.

Node.js MongoDB Insert Record

A record, or document can be inserted into MongoDB collection using the insertOne() method. It takes an object containing keys(s) and value(s) of each field in the document as first parameter, and a callback function as second parameter where you can work with any errors, or the result of the insertion.

Example :- Let’s insert a record or document in “employees” collection.

Step 1:- Let’s, create a node_mongo_insert.js file and put the following code in it –

Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.

you will see following output on terminal –

Output:-

Insert Multiple Records

The insertMany() method is used to insert multiple records in a MongoDB collection. It takes array of objects that contain the records or documents you want to insert.

Step 1:- Let’s, create a node_mongo_multi_insert.js file and put the following code in it –

Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.

you will see following output on terminal –

Output:-

The Result Object

insertMany() method, returns a result object which holds the information about how the insertion affected the database.

Example:- The insertedCount property returns the number of document inserted

Output:-

The _id Field

The _id Field is used to assign an unique id to each of the document or records in a collection. If you don’t specifies it the MongoDB engine will assign a unique id for each of the document. You can also specify it and it must be unique for each of the document.

 

 

In this tutorial we have learn about the Nodejs MongoDB Insert Record and its application with practical example. I hope you will like this tutorial.