Operations like create database, Create Collection in database, , insert multiple data in collection.
//create database:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if(err) throw err;
console.log('Database is created successfully');
db.close();
});
//create collection
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if(err) throw err;
var dbo = db.db('mydb');
dbo.createCollection("customers",function(err, res){
if(err) throw err;
console.log("collection is created..");
db.close();
});
});
//insert multiple data into collection:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if(err) throw err;
var dbo = db.db('mydb');
var myobj = [
{name:"x",roll:"1"},
{name:"y",roll:"2",},
{name:"z",roll:"3",},
{name:"a",roll:"4",},
{name:"r",roll:"5",},
{name:"c",roll:"6",}
];
dbo.collection('customers').insertMany(myobj, function(err, res){
if(err) throw err;
console.log("NUMBER OF DOCUMENT INSERTED: " + res.insertedCount);
db.close();
});
});
*****************To Be Continued*****************
Tags:
mongodb