Node & MongoDB – Insert Document


Node & MongoDB – Insert Document



”;


To insert document(s) in a collection of a database, you can use collection.insertOne() or collection.insertMany() methods to insert one or multiple documents.


database.collection("sampleCollection").insertOne(firstDocument, function(error, res) {
   if (error) throw error;
   console.log("1 document inserted");
});
database.collection("sampleCollection").insertMany(documents, function(error, res) {
   if (error) throw error;
   console.log("Documents inserted: " + res.insertedCount);
});

Example

Try the following example to insert documents in a mongodb collection −

Copy and paste the following example as mongodb_example.js −


const MongoClient = require(''mongodb'').MongoClient;
// Prepare URL
const url = "mongodb://localhost:27017/";
const firstDocument = {
   First_Name : ''Mahesh'',
   Last_Name : ''Parashar'',
   Date_Of_Birth: ''1990-08-21'',
   e_mail: ''[email protected]'',
   phone: ''9034343345''
};
const documents = [{
   First_Name : ''Radhika'',
   Last_Name : ''Sharma'',
   Date_Of_Birth: ''1995-09-26'',
   e_mail: ''[email protected]'',
   phone: ''9000012345''
},
{
   First_Name : ''Rachel'',
   Last_Name : ''Christopher'',
   Date_Of_Birth: ''1990-02-16'',
   e_mail: ''[email protected]'',
   phone: ''9000054321''
},
{
   First_Name : ''Fathima'',
   Last_Name : ''Sheik'',
   Date_Of_Birth: ''1990-02-16'',
   e_mail: ''[email protected]'',
   phone: ''9000012345''
}
];
// make a connection to the database
MongoClient.connect(url, function(error, client) {
   if (error) throw error;
   console.log("Connected!");
   // Connect to the database
   const database = client.db(''myDb'');
   database.collection("sampleCollection").insertOne(firstDocument, function(error, res) {
      if (error) throw error;
      console.log("1 document inserted");
   });
   database.collection("sampleCollection").insertMany(documents, function(error, res) {
      if (error) throw error;
      console.log("Documents inserted: " + res.insertedCount);
   }); 
   // close the connection
   client.close();
});

Output

Execute the mysql_example.js script using node and verify the output.


node mongodb_example.js
Documents inserted: 3
1 document inserted

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *