Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 3 (Part B)

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

Unit-3(part-B)

Mongo db
Managing Collections
• As a database admin, you may also find
yourself administering collections within a
database.
• Displaying a List of Collections in a Database
use test
show collections
Creating Collections
• To create a collection, you need to call
createCollection(name, [options]) on the
database handle. The name parameter is the
name of the new database.
• The optional options parameter is an object
that can have the properties
Options example
• capped A Boolean; when true, the collection is
a capped collection that does not grow bigger
than the maximum size specified by the size
attribute. Default: false
• autoIndexID A Boolean; when true, an _id field
is automatically created for each document
added to the collection and an index on that
field is implemented. This should be false for
capped collections. Default: true.
Creating a new collection in the MongoDB
console shell
• db.createCollection("newCollection")
Deleting Collections
• Removing old collections frees up disk space
and eliminates any overhead such as indexing
associated with the collection.
Finding Documents in a Collection

• Most of the time you use a library such as the native


MongoDB driver or Mongoose to access documents in
a collection.
• find(query) method---returns documents based on
queries.
• Find() method—returns all the documents .
• Example use testDB
• coll = db.getCollection("newCollection")
• coll.find()
• coll.find({speed:"120mph"})
Finding documents in the collections
Adding Documents to a Collection
Deleting Documents in a Collection
Updating Documents in a Collection
• To update documents in a collection, you need
to get the collection. Then you can use a
couple of different methods:
• The save(object) method saves changes that
you have made to an object,
• the update(query, update, options) method
queries for documents in the collection and
then updates them as they are found.
The options parameter of update() is an
object that has two properties
• —multi and upsert—that are both Boolean
values.
• If upsert is true, a new document is created if
none are found.
• If multi is true, all documents that match the
query are updated; otherwise, only the first
document is updated
Updating Documents in a Collection
Connecting node js and mongo db
var MongoClient = require('mongodb').MongoClient;
var url ='mongodb://localhost:27017/aaru';
MongoClient.connect(url, function(url,err, db) {
if (err){
console.log("Connection Failed Via Client Object.");
} else {
console.log("Connected Via Client Object . . .");
console.log("Connection closed . . .");

}
});
Adding the MongoDB Driver to Node.js

• From your project root directory, execute the follow


• npm install mongodb
• A node_modules directory is created(using npm
init) if it is not already there, and the mongodb
driver module is installed under it.
• Once that is done, your Node.js application files can
use the require('mongodb') command to access the
mongodb module functionalitying command using a
console prompt
Connecting to MongoDB from Node.js
• Accessing MongoDB is best done through the
MongoClient class in the mongodb module.
• This class provides two main methods to create
connections to MongoDB.
• One is to create an instance of the MongoClient
object and then use that object to create and
manage the MongoDB connection.
• The other method uses a connection string to
connect. Either of these options works well.
Connecting to MongoDB from Node.js
• To connect to MongoDB via a MongoClient
object, first create an instance of the
MongoClient object using the following
syntax: var client = new MongoClient();
• After you have created the MongoClient, you
still need to open a connection to the
MongoDB server database using the
connect(url, options, callback) method.
Connection syntax
• mongodb://
[username:password@]host[:port][/
[database][?options]]
• For example, to connect to a MongoDB
database named MyDB on a host named
MyDBServer on port 8088, you would use the
following URL:
client.connect('mongodb://MyDBServer:8088/
MyDB');
Authentication
• var MongoClient = require('mongodb').MongoClient, 0
• Server = require('mongodb').Server;
• var client = new MongoClient();
• client.connect('mongodb://localhost:27017'),
• { poolSize: 5, reconnectInterval: 500, }, 06 function(err, db) {
• if (err){
• console.log("Connection Failed Via Client Object."); } else {
• var db = db.db("testDB");
• } if (db){
• console.log("Connected Via Client Object . . .");
• db.authenticate("dbadmin", "test", function(err, results){
• if (err){
• console.log("Authentication failed . . .");
• db.close();
• console.log("Connection closed . . .");
• } else {
• console.log("Authenticated Via Client Object . . .");
• db.logout(function(err, result) {
• if(!err){
• console.log("Logged out Via Client Object . . ."); }
• db.close();
• console.log("Connection closed . . ."); });
• });
• }
output
• Connected Via Client Object . . . Authenticated
Via Client Object . . . Logged out Via Client
Object . . .

Connection closed . . .
Understanding the Objects Used in the
MongoDB Node.js Driver
• Understanding the Db Object
• Understanding the Collection Object
• Example
var collection = db.collection()
var collection = new Collection(db,
"myCollection")
db.createCollection("newCollection",
function(err, collection){ }
Understanding the Admin Object
• var adminDb = db.admin()
• var adminDb = new Admin(db)

• Understanding cursor objects


• For example, when you use find(), the actual
documents are not returned in the callback
function but a Cursor object instead. You can
then use the Cursor object to read the items in
the results.
Accessing and Manipulating Databases

• Listing Databases
• MongoClient.connect("mongodb://localhost/admin",
function(err, db) {
• var adminDB = db.admin();
• adminDB.listDatabases(function(err, databases)
{ console.log("Before Add Database List: ");
console.log(databases);
• });
• });
Creating a Database

• var MongoClient = require('mongodb').MongoClient;


• var url = "mongodb://127.0.0.1:27017/";
• MongoClient.connect(url,function(_err, Db) {
• var newDB = Db.db("newDB");
• newDB.createCollection("newCollection", function(err,
_collection){
• if(!err){
• console.log("New Database and Collection Created");
• }
• });
• });
Deleting db
• db.db("newDB").dropDatabase(function(err, results){
• Getting the Status of the MongoDB Server
• var adminDB = db.admin();
• adminDB.serverStatus(function(err, status)
• Output
version: '3.4.2', process: 'mongod', pid: 2612,
uptime: 44775,
uptimeMillis: 44774694,
uptimeEstimate: 44774,
localTime: 2017-08-11T19:02:25.086Z,
asserts: { regular: 0, warning: 0, msg: 0, user: 0, rollovers: 0
connections: { current: 1, available: 999999, totalCreated: 8 }, extra_info
Deleting collections
• Deleting Collections
• newDB.dropCollection("newCollection",
function(err, result)

You might also like