Node.js - Insert Document(s) to MongoDB Collection - Examples
嚜燒ode.js 每 Insert Document(s) to MongoDB Collection 每 Examples
Node.js 每 Insert Document(s) to MongoDB Collection
In this Node.js Tutorial, we shall learn to insert one or more documents to MongoDB Collection from Node.js
Application, using insertOne() and insertMany() method respectively, with examples.
Following is a step by step guide with an example to insert documents to MongoDB Collection from Node.js
Application.
1. Start MongoDB Service. Run the following command to start MongoDB Service
sudo service
mongod start
sudo service mongod start
2. Get the base URL to MongoDB Service. A simple hack to know the base url of MongoDB Service is to Open a Terminal and
run Mongo Shell.
Terminal - Mongo Shell
arjun@nodejs:~$
mongo
MongoDB shell version
v3.4.9
connecting
to: mongo
arjun@nodejs:~$
mongodb://127.0.0.1:2
MongoDB shell version v3.4.9
7017
MongoDB
connectingserver
to: mongodb://127.0.0.1:27017
version: 3.4.9
MongoDB
Server
has server
startupversion: 3.4.9
warnings:
Server has startup warnings:
2017-1029T18:15:36.110+0530
2017-10-29T18:15:36.110+0530 I STORAGE [initandlisten]
I STORAGE
[initandlisten]
While the Mongo Shell starts up, it echoes back the base url of MongoDB.
mongodb://127.0.0.1:2
7017
mongodb://127.0.0.1:27017
3. Prepare the complete URL. Append the Database name you want to connect to (say newdb), to the base URL.
mongodb://127.0.0.1:2
7017/newdb
mongodb://127.0.0.1:27017/newdb
4. Create a MongoClient.
var MongoClient =
require('mongodb').Mon
goClient;
var MongoClient = require('mongodb').MongoClient;
5. Make connection from MongoClient to the MongoDB Server with the help of URL.
MongoClient.connect(u
rl,
);
MongoClient.connect(url, );
Once the MongoClient is done trying to make a connection, the callback function receives error and db object as arguments.
If the connection is successful, the db object points to the database, newdb.
6. Insert documents to specified MongoDB Collection. Following is the syntax of insertOne() and insertMay() methods used to
insert documents to collection in MongoDB from Node.js. insertOne()
db.collection().insertOne(<
document>,
)
db.collection().insertOne(, )
insertMany()
db.collection().insertMany(
,
)
db.collection().insertMany(, )
Name of the new MongoDB Collection, that we would like to create
Single document that has to be inserted to MongoDB Collection
Array of documents to be inserted to MongoDB Collection
This Node.js Callback Function is called after Node has tried creating a collection, and ready
with the result. The callback function receives error and result object as arguments.
insertOne() 每 Example Node.js program
node-js-mongodb-insert-document.js
// we create 'users'
collection in newdb
database
var url =
"mongodb://localhost:2
7017/newdb";
// we create 'users' collection in newdb database
var url = "mongodb://localhost:27017/newdb";
// create a client to mongodb
var MongoClient = require('mongodb').MongoClient;
// make client connect to mongo service
MongoClient.connect(url, function(err, db) {
if (err) throw err;
// db pointing to newdb
console.log("Switched to "+db.databaseName+" database");
// document to be inserted
var doc = { name: "Roshan", age: "22" };
// insert document to 'users' collection using insertOne
db.collection("users").insertOne(doc, function(err, res) {
if (err) throw err;
console.log("Document inserted");
// close the connection to db when you are done with it
db.close();
});
});
Output
$ node node-jsmongodb-insertdocument.js
Switched to newdb
database
$ node node-js-mongodb-insert-document.js
Document inserted
Switched to newdb database
Document inserted
Mongo Shell
> use newdb
switched to db newdb
> show collections
users
>>db.users.find({});
use newdb
{ "_id" :
switched to db newdb
ObjectId("5a127729a41
5612642e3d6ad"),
> show collections
"name" : "Roshan",
users : "22" }
"age"
>
> db.users.find({});
{ "_id" : ObjectId("5a127729a415612642e3d6ad"), "name" : "Roshan", "age" : "22" }
>
insertMany() 每 Example Node.js program
node-js-mongodb-insert-many-documents.js
// we create 'users'
collection in newdb
database
var url =
"mongodb://localhost:2
// we create 'users' collection in newdb database
7017/newdb";
var url = "mongodb://localhost:27017/newdb";
// create a client to
mongodb
// create
a client=to mongodb
var
MongoClient
require('mongodb').Mon
var MongoClient = require('mongodb').MongoClient;
goClient;
// make client connect
// mongo
make client
connect to mongo service
to
service
MongoClient.connect(u
MongoClient.connect(url, function(err, db) {
rl, function(err, db) {
if (err)
throw
if (err)
throw
err;err;
// db
pointing
to to newdb
// db pointing
newdb
console.log("Switched
console.log("Switched to "+db.databaseName+" database");
to
"+db.databaseName+"
database");
// documents to be inserted
var docs = [{
"Udat", age: "21" },
// documents
to name:
be
inserted
{ name: "Karthik", age: "24" },
var docs = [{ name:
name:
"Udat", age: {"21"
}, "Anil", age: "23" }];
{ name: "Karthik",
age: "24" },
{//name:
age:
insert "Anil",
multiple
documents to 'users' collection using insertOne
"23" }];
db.collection("users").insertMany(docs, function(err, res) {
// insert
multiple
if (err)
throw err;
documents to 'users'
console.log(res.insertedCount+"
documents inserted");
collection
using
insertOne
// close the connection to db when you are done with it
db.collection("users").i
nsertMany(docs,
db.close();
function(err, res) {
if });
(err) throw err;
});
console.log(res.inserte
dCount+" documents
inserted");
// close the
Output
connection to db when
you are done with it
$ db.close();
node node-jsmongodb-insert-many});
documents.js
});
Switched to newdb
database
$ node node-js-mongodb-insert-many-documents.js
3 documents inserted
Switched to newdb database
3 documents inserted
Mongo Shell
> db.users.find({});
{ "_id" :
ObjectId("5a127729a41
5612642e3d6ad"),
"name" : "Roshan",
"age" : "22" }
{ "_id" :
ObjectId("5a1278efecc
5062794f4ed8d"),
> db.users.find({});
{ "_id" : ObjectId("5a127729a415612642e3d6ad"), "name" : "Roshan", "age" : "22" }
{ "_id" : ObjectId("5a1278efecc5062794f4ed8d"), "name" : "Udat", "age" : "21" }
{ "_id" : ObjectId("5a1278efecc5062794f4ed8e"), "name" : "Karthik", "age" : "24" }
{ "_id" : ObjectId("5a1278efecc5062794f4ed8f"), "name" : "Anil", "age" : "23" }
The first entry was from first example, and the rest three have been inserted with this example.
Reference
MongoDB Tutorial 每 Learn MongoDB from basics with Examples.
Conclusion :
In this Node.js MongoDB tutorial : Node.js 每 Insert Document(s) to MongoDB Collection, we have learnt to
insert one or more documents to MongoDB Collection using insertOne() and insertMany() methods, from
Node.js Application using mongodb package. In our next tutorial 每 Node.js MongoDB Find, we shall learn to
query documents from MongoDB Collection.
Node.js
?
Node.js Tutorial
Get Started W ith Node.js
?
Install Node.js Ubuntu Linux
?
Install Node.js Windows
?
Node.js - Basic Example
?
Node.js - Command Line Arguments
?
Node.js - Modules
?
Node.js - Create a module
?
Node.js - Add new functions to Module
?
Node.js - Override functions of Module
?
Node.js - Callback Function
?
Node.js - forEach
Express.js
?
Express.js Tutorial
?
What is Express.js?
?
Express.js Application Example
?
Install Express.js
?
Express.js Routes
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- extra notes client side design and development an
- harnessing location with and oracle database
- nosql injection owasp
- insert document s to mongodb collection examples
- mongodb express angularjs node
- microservices with node
- node js syllabus deccansoft
- cheat sheet and version 1 02
- and backend development github pages