Skip to content
Related Articles

Related Articles

Improve Article

How to push data in a MongoDB document ?

  • Last Updated : 18 May, 2021

The insertOne() and insertMany() are the two methods of the MongoDB module in node.js that are used to push the documents in the collections of the MongoDB database. The insertOne() method inserts one data at a time into the collection and insertMany() method inserts multiple data into the collection of the MongoDB database. In this article, we will discuss how to push data in MongoDB collection using MongoDB module methods.

Installing module: You can install mongodb module using the following command. 

node install mongodb

Project Structure: It will look like the following.

Running Server on Local IP: Data is the directory where MongoDB server is present.



mongod --dbpath=data --bind_ip 127.0.0.1

index.js




const MongoClient = require("mongodb");
  
// Server running 
  
// Database name
const databasename = "GFG";
  
MongoClient.connect(url).then((client) => {
  
    // Connecting to the database
    const connect = client.db(databasename);
  
     // Database collection
    const collection = connect
        .collection("GFGcollections");
  
    // Inserting single document
    collection.insertOne({ 
        "name": "aayush", "class": "GFG" });
  
    // Inserting multiple document
    collection.insertMany([
        { "name": "saini", "class": "GFG" }, 
        { "name": "GfGnew", "class": "GFGNEW" }
    ]);
  
    console.log("Insertion Successfull")
}).catch(err) => {
      
    // If error occured show the error message
    console.log(err.Message);
}

Run index.js file using the following command:

node index.js

Output:

MongoDB Database:




My Personal Notes arrow_drop_up
Recommended Articles
Page :