Open In App

How to push data in a MongoDB document ?

Improve
Improve
Like Article
Like
Save
Share
Report

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 Successful")
}).catch(err) => {
      
    // If error occurred show the error message
    console.log(err.Message);
}


Run index.js file using the following command:

node index.js

Output:

MongoDB Database:



Last Updated : 15 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads