insertmany mongodb nodejs code example

Example 1: insert into mongodb node js

//CRUD

const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;

const connectionURl = 'mongodb://127.0.0.1:27017';
const databaseName = 'task-manager';

MongoClient.connect(
	connectionURl,
	{ useNewUrlParser: true },
	(error, client) => {
		if (error) {
			return console.log('unable to connect to database');
		}

		const db = client.db(databaseName);

		db.collection('users').insertOne({
			name: 'user',
			age: 24,
		});
	}
);

Example 2: insertMany mongodb nodejs

const { MongoClient } = require("mongodb");
// Replace the uri string with your MongoDB deployment's connection string.
const uri =
  "mongodb+srv://:@?writeConcern=majority";
const client = new MongoClient(uri);
async function run() {
  try {
    await client.connect();
    const database = client.db("sample_mflix");
    const movies = database.collection("movies");
    // create an array of documents to insert
    const docs = [
      { name: "Red", town: "Kanto" },
      { name: "Blue", town: "Kanto" },
      { name: "Leon", town: "Galar" }
    ];
    // this option prevents additional documents from being inserted if one fails
    const options = { ordered: true };
    const result = await movies.insertMany(docs, options);
    console.log(`${result.insertedCount} documents were inserted`);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

Example 3: mongodb js insertmany

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
var data1={
    name:'Data1',
    work:'student',
    No:4355453,
    Date_of_birth:new Date(1996,10,17)
};

var data2={
    name:'Data2',
    work:'student',
    No:4355453,
    Date_of_birth:new Date(1996,10,17)
};

MongoClient.connect(url, function(err, db) {
    if(err!=null){
        return console.log(err.message)
    }

    //insertOne
    db.collection("App").insertOne(data1,function (err,data) {

        if(err!=null){
            return console.log(err);
        }
        console.log(data.ops[0]);
    });

    //insertMany

var Data=[data1,data2];

db.collection("App").insertMany(Data,forceServerObjectId=true,function (err,data) {

        if(err!=null){
            return console.log(err);
        }
        console.log(data.ops);
    });
    db.close();
});

Tags: