MongoDB’s document is like a table’s row in RDBMS. to insert document into the collection through insertOne() or insertMany() method.
Insert one document through insertOne() method
Firstly create the insert_document.js file.
var MongoClient = require('mongodb').MongoClient;
let url="mongodb://localhost:27017/";
var options = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
MongoClient.connect(url,options, function (err, connection_obj) {
try{
if (err) throw err;
var dbo = connection_obj.db("users_management");
var user_obj={name:"John",age:35}
dbo.collection("users").insertOne(user_obj, function(err, res) {
if (err) throw err;
console.log("1 document is added into collection");
console.log(res.ops);
console.log(res.insertedCount);
connection_obj.close();
});
}catch(err){
console.log("connection fails");
}
Now, run the insert_document.js file.
node insert_document.js
Output:-
1 document is added into collection
[ { name: ‘John’, age: 35, _id: 5fdc9e76304b8b785feb4ebf } ]
1
[ { name: ‘John’, age: 35, _id: 5fdc9e76304b8b785feb4ebf } ]
1
Insert multiple documents through insertMany() method
Firstly create the insert_documents.js file.
var MongoClient = require('mongodb').MongoClient;
let url="mongodb://localhost:27017/";
var options = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
MongoClient.connect(url,options, function (err, connection_obj) {
try{
if (err) throw err;
var dbo = connection_obj.db("users_management");
var user_obj=[{name:"Rom",age:31},{name:"Mathew",age:32},{name:"Sachin",age:38}];
dbo.collection("users").insertMany(user_obj, function(err, res) {
if (err) throw err;
console.log("documents are added into collection");
console.log(res.ops);
console.log(res.insertedCount);
connection_obj.close();
});
}catch(err){
console.log("connection fails");
}
Now, run the insert_documents.js file.
node insert_documents.js
Output:-
documents are added into collection
[ { name: ‘Rom’, age: 31, _id: 5fdcdb87b6dad382104b0f86 },
{ name: ‘Mathew’, age: 32, _id: 5fdcdb87b6dad382104b0f87 },
{ name: ‘Sachin’, age: 38, _id: 5fdcdb87b6dad382104b0f88 } ]
3
[ { name: ‘Rom’, age: 31, _id: 5fdcdb87b6dad382104b0f86 },
{ name: ‘Mathew’, age: 32, _id: 5fdcdb87b6dad382104b0f87 },
{ name: ‘Sachin’, age: 38, _id: 5fdcdb87b6dad382104b0f88 } ]
3