SlideShare a Scribd company logo
MongoDB + Node.js
Building first app with MongoDB and Node.js
2
Agenda
MongoDB + Node.js
Driver
ODM's
MEAN Stack
Meteor
3
Ola, I'm Norberto!
Norberto Leite
Technical Evangelist
Madrid, Spain
@nleite
norberto@mongodb.com
http://www.mongodb.com/norberto
MongoDB Node.js
INFACT
MongoDB JavaScript
7
Few reasons why
Flexible Agile
Web
Language
8
MongoDB + Javascript
•  MongoDB Shell
–  JS interperter
•  MongoDB MapReduce
–  Runs on top of V8
–  Map and Reduce functions are JS functions
•  Native support for Node.js
–  One of the most used Drivers out there!
–  https://www.npmjs.com/package/mongodb
Node.js
10
2 Foundations
Events Streams
11
2 Foundations
•  Events / Event Loop
–  Single Thread Applications
–  No threads
–  Events Emitter
–  Event Queue
–  Known Events
•  Streams
–  Read, Write, Both
–  Unix Pipes
–  We use it extensively!
Install
npm package
$ npm install mongodb
Compatibility
http://docs.mongodb.org/ecosystem/drivers/node-js/#compatibility
15
Compatibility w/ MongoDB
Initialize Project
package.json file
$ mkdir firstappnodejs
$ cd firstappnodejs
$ npm init
package.json file
$ mkdir firstappnodejs
$ cd firstappnodejs
$ npm init
...
{
"name": "firstappnodejs",
"version": "0.0.1",
"description": "Small demo webinar application",
"main": "index.js",
"scripts": {
"test": "workitout"
},
"repository": {
"type": "git",
"url": "git://github.com/nleite/firstappnodejs"
},
"dependencies": {
"mongodb": "~2.0"
},
"keywords": [http://docs.mongodb.org/ecosystem/drivers/node-js/#compatibility
"demo",
"nodejs",
"mongodb"
],
"author": "Norberto Leite",
"license": "Apache 2.0",
"bugs": {
"url": "https://github.com/nleite/firstappnodejs/issues"
},
"homepage": "https://github.com/nleite/firstappnodejs"
package.json file
$ mkdir firstappnodejs
$ cd firstappnodejs
$ npm init
...
{
"name": "firstappnodejs",
"version": "0.0.1",
"description": "Small demo webinar application",
"main": "index.js",
"scripts": {
"test": "workitout"
},
"repository": {
"type": "git",
"url": "git://github.com/nleite/firstappnodejs"
},
"dependencies": {
"mongodb": "~2.0"
},
"keywords": [
"demo",
"nodejs",
"mongodb"
],
"author": "Norberto Leite",
"license": "Apache 2.0",
"bugs": {
"url": "https://github.com/nleite/firstappnodejs/issues"
},
"homepage": "https://github.com/nleite/firstappnodejs"
Install our new firstappnodejs app!
$ npm install
> kerberos@0.0.10 install …
…
> bson@0.3.1 install
> mongodb@2.0.28 node_modules/mongodb
├── readable-stream@1.0.31 (isarray@0.0.1, inherits@2.0.1,
string_decoder@0.10.31, core-util-is@1.0.1)
└── mongodb-core@1.1.25 (kerberos@0.0.10, bson@0.3.1)
firstappnodejs/ $ ls
node_modules package.json
Connect
boot up MongoDB Server
$ mkdir ~/firstappdb
$ mongod --dbpath ~/firstappdb
boot up MongoDB Server
$ mkdir ~/firstappdb
$ mongod --dbpath ~/firstappdb --auth
--keyfile ~/n.pem
https://www.mongodb.com/products/mongodb-enterprise-advanced
boot up MongoDB Server
$ mkdir ~/firstappdb
$ mongod --dbpath ~/firstappdb --auth
--keyfile ~/n.pem
https://www.mongodb.com/products/mongodb-enterprise-advanced
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
Connect
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
//connection uri
var uri = "mongodb://localhost:27017/firstapp"
Connect
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
//connection uri
var uri = "mongodb://localhost:27017/firstapp"
//connect to MongoDB
MongoClient.connect(uri, function(err, db){
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});
Connect
28
Connection Pooling
•  No traditional Pooling mechanism
–  Single thread process
•  Sockets to pipeline operations
•  Failover
–  Buffering up operations
–  bufferMaxEntries
–  numberOfRetries
–  retryMiliSeconds
http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html
CRUD
var insertDocuments = function(db, cb){
//we don't need to explicitly create a collection
var collection = db.collection('myCollection');
collection.insertMany([
{"mongodb": "is just awesome"},
{"nodejs": "so awesome"}
], function(err, result){
assert.equal(null, err);
//inserted 2 documents
assert.equal(2, result.insertedCount);
//invoke callback
cb(result);
});
}
Insert
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
var insertDocuments = function(db, cb){
//we don't need to explicitly create a collection
var collection = db.collection('myCollection');
collection.insertMany([
{"mongodb": "is just awesome"},
{"nodejs": "so awesome"}
], function(err, result){
assert.equal(null, err);
//inserted 2 documents
assert.equal(2, result.insertedCount);
//invoke callback
cb(result);
});
}
Insert
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
var insertDocuments = function(db, cb){
//we don't need to explicitly create a collection
var collection = db.collection('myCollection');
collection.insertMany([
{"mongodb": "is just awesome"},
{"nodejs": "so awesome"}
], function(err, result){
assert.equal(null, err);
//inserted 2 documents
assert.equal(2, result.insertedCount);
//invoke callback
cb(result);
});
}
Insert
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
var insertDocuments = function(db, cb){
//we don't need to explicitly create a collection
var collection = db.collection('myCollection');
collection.insertMany([
{"mongodb": "is just awesome"},
{"nodejs": "so awesome"}
], function(err, result){
assert.equal(null, err);
//inserted 2 documents
assert.equal(2, result.insertedCount);
//invoke callback
cb(result);
});
}
Insert
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
MongoClient.connect(uri, function(err, db) {
assert.equal(null, err);
console.log("Sweet! Talking to Server");
insertDocuments(db, function() {
db.close();
});
});
Insert
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
MongoClient.connect(uri, function(err, db) {
assert.equal(null, err);
console.log("Sweet! Talking to Server");
insertDocuments(db, function() {
db.close();
});
});
Insert
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
var updateDocument = function(db, cb){
var collection = db.collection("myCollection");
collection.updateOne( {"mongodb": "is just awesome"},
{$set: {"users": ["nleite"]}}, function( err, result){
assert.equal(null, err);
assert.equal(1, result.modifiedCount);
console.log("Cool, just updated");
cb(result);
});
}
Update
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
var updateDocument = function(db, cb){
var collection = db.collection("myCollection");
collection.updateOne( {"mongodb": "is just awesome"},
{$set: {"users": ["nleite"]}}, function( err, result){
assert.equal(null, err);
assert.equal(1, result.modifiedCount);
console.log("Cool, just updated");
cb(result);
});
}
Update
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
var updateDocument = function(db, cb){
var collection = db.collection("myCollection");
collection.updateOne( {"mongodb": "is just awesome"},
{$set: {"users": ["nleite"]}}, function( err, result){
assert.equal(null, err);
assert.equal(1, result.modifiedCount);
console.log("Cool, just updated");
cb(result);
});
}
Update
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
var updateDocument = function(db, cb){
var collection = db.collection("myCollection");
collection.updateOne( {"mongodb": "is just awesome"},
{$set: {"users": ["nleite"]}}, function( err, result){
assert.equal(null, err);
assert.equal(1, result.modifiedCount);
console.log("Cool, just updated");
cb(result);
});
}
Update
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
MongoClient.connect(uri, function(err, db) {
assert.equal(null, err);
console.log("Ok, I can now update!");
updateDocuments(db, function() {
db.close();
});
});
Update
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
Remove
var removeDocument = function(db, cb){
var collection = db.collection("myCollection");
collection.deleteOne( {"users": "nleite"},
function( err, result){
assert.equal(null, err);
assert.equal(1, result.deletedCount);
console.log("purged the @nleite contaminated
data!");
cb(result);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove
Remove
var removeDocument = function(db, cb){
var collection = db.collection("myCollection");
collection.deleteOne( {"users": "nleite"},
function( err, result){
assert.equal(null, err);
assert.equal(1, result.deletedCount);
console.log("purged the @nleite contaminated
data!");
cb(result);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove
Remove
var removeDocument = function(db, cb){
var collection = db.collection("myCollection");
collection.deleteOne( {"users": "nleite"},
function( err, result){
assert.equal(null, err);
assert.equal(1, result.deletedCount);
console.log("purged the @nleite contaminated
data!");
cb(result);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove
Remove
MongoClient.connect(uri, function(err, db) {
assert.equal(null, err);
console.log("Ok, I can now delete!");
removeDocuments(db, function() {
db.close();
});
});
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove
Find
var findAllDocuments = function(db, cb){
var collection = db.collection('myDocuments');
//or collection.find()
collection.find({}).toArray(function(err, docs){
assert.equal(err, null);
assert.equal(1, docs.length);
console.log("Gotcha! found "+ docs.length);
console.dir(docs);
cb(docs);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#find
Find
var findAllDocuments = function(db, cb){
var collection = db.collection('myDocuments');
//or collection.find()
collection.find({}).toArray(function(err, docs){
assert.equal(err, null);
assert.equal(1, docs.length);
console.log("Gotcha! found "+ docs.length);
console.dir(docs);
cb(docs);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#find
Find
var findAllDocuments = function(db, cb){
var collection = db.collection('myDocuments');
//or collection.find()
collection.find({}).toArray(function(err, docs){
assert.equal(err, null);
assert.equal(1, docs.length);
console.log("Gotcha! found "+ docs.length);
console.dir(docs);
cb(docs);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#find
Flexibility
Schema Flexibility
Different Schemas
var insertDifferentShapes = function(db, cb){
var doc1 = {"name": "Norberto", "talks": [
{"nodejs":10}, {"java":15}, "python":11]};
var doc2 = {"name": "Bryan", "webinars": 30};
var coll = db.collection("content")
coll.insertMany( [doc1, doc2], function(err, result){
assert.equal(err, null);
assert.equal(2, result.insertedCount);
console.log("Sweet, inserted "+ result.insertedCount);
cb(result);
});
}
http://docs.mongodb.org/manual/data-modeling/
Different Schemas
var insertDifferentShapes = function(db, cb){
var doc1 = {"name": "Norberto", "talks": [
{"nodejs":10}, {"java":15}, "python":11]};
var doc2 = {"name": "Bryan", "webinars": 30};
var coll = db.collection("content")
coll.insertMany( [doc1, doc2], function(err, result){
assert.equal(err, null);
assert.equal(2, result.insertedCount);
console.log("Sweet, inserted "+ result.insertedCount);
cb(result);
});
}
http://docs.mongodb.org/manual/data-modeling/
WriteConcerns
WriteConcern w:1
WriteConcern w:2
WriteConcern j:true
Different WriteConcerns
var insertSuperImportant = function(db, cb){
var customer = {"name": "Manny Delgado", "age": 14};
var coll = db.collection("customers");
var writeConcern = {"w": "majority"};
col.insertOne( customer, writeConcern, function(err, result){
assert.equal(err, null);
assert.equal(1, result.insertedCount);
console.log("Inserted super important record");
cb(result);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/WriteConcernError.html
Different WriteConcerns
var insertSuperImportant = function(db, cb){
var customer = {"name": "Manny Delgado", "age": 14};
var coll = db.collection("customers");
var writeConcern = {"w": "majority"};
col.insertOne( customer, writeConcern, function(err, result){
assert.equal(err, null);
assert.equal(1, result.insertedCount);
console.log("Inserted super important record");
cb(result);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/WriteConcernError.html
Read Preference
59
Read Preference
•  Read from Primary (default)
ReadPreference.PRIMARY
•  Read from Primary Preferably
ReadPreference.PRIMARY_PREFERRED
•  Read from Secondary
ReadPreference.SECONDARY
•  Read from Secondary Preferably
ReadPreference.SECONDARY_PREFERRED
•  Read from Nearest Node
ReadPreference.NEAREST
http://mongodb.github.io/node-mongodb-native/2.0/api/ReadPreference.html
Read From Nearest
var readNearestWaterMelonColor = function(db, cb){
var rp = ReadPreference.NEAREST;
var coll = db.collection("products", {ReadPreference:rp});
var query = {"color": "water melon green"};
collection.find(query).toArray(function(err, docs){
assert.equal(err, null);
assert.equal(1, docs.length);
console.log("So many products: "+ docs.length);
console.dir(docs);
cb(docs);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/ReadPreference.html
Read From Nearest
var readNearestWaterMelonColor = function(db, cb){
var rp = ReadPreference.NEAREST;
var coll = db.collection("products", {ReadPreference:rp});
var query = {"color": "water melon green"};
collection.find(query).toArray(function(err, docs){
assert.equal(err, null);
assert.equal(1, docs.length);
console.log("So many products: "+ docs.length);
console.dir(docs);
cb(docs);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/ReadPreference.html
Read From Nearest
var readNearestWaterMelonColor = function(db, cb){
var rp = ReadPreference.NEAREST;
var coll = db.collection("products", {readPreference:rp});
var query = {"color": "water melon green"};
collection.find(query).toArray(function(err, docs){
assert.equal(err, null);
assert.equal(1, docs.length);
console.log("So many products: "+ docs.length);
console.dir(docs);
cb(docs);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/ReadPreference.html
Aggregation
Aggregation
var aggregateAvgAgeGender = function( db, cb){
//{age:XX, name:"user name", gender: "M/F"}
var pipeline = [
{$group: { "_id": "$gender", avg_age: {$avg: "$age"}}},
];
var coll = db.collection("users");
var cursor = coll.aggregate(pipeline);
cursor.forEach( function(x){
console.log("Gender " + x._id + " age average " + x.avg_age)
}, function(x) {
cb(cursor);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#aggregate
Aggregation
var aggregateAvgAgeGender = function( db, cb){
//{age:XX, name:"user name", gender: "M/F"}
var pipeline = [
{$group: { "_id": "$gender", avg_age: {$avg: "$age"}}},
];
var coll = db.collection("users");
var cursor = coll.aggregate(pipeline);
cursor.forEach( function(x){
console.log("Gender " + x._id + " age average " + x.avg_age)
}, function(x) {
cb(cursor);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#aggregate
Aggregation
var aggregateAvgAgeGender = function( db, cb){
//{age:XX, name:"user name", gender: "M/F"}
var pipeline = [
{$group: { "_id": "$gender", avg_age: {$avg: "$age"}}},
];
var coll = db.collection("users");
var cursor = coll.aggregate(pipeline);
cursor.forEach( function(x){
console.log("Gender " + x._id + " age average " + x.avg_age)
}, function(x) {
cb(cursor);
});
}
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#aggregate
Aggregation
var aggregateAvgAgeGender = function( db, cb){
//{age:XX, name:"user name", gender: "M/F"}
var pipeline = [
{$match:{"age": $gt: 18}},
{$group: { "_id": "$gender", avg_age: {$avg: "$age"}}},
{$project:{"ID": "$_id", "average": "$avg_age" }}
];
var cursor = coll.aggregate(pipeline);
var coll = db.collection("users");
cursor.forEach( function(x){
console.log("Gender " + x._id + " age average " + x.avg_age)
}, function(x) {
cb(cursor);
});}
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#aggregate
ODM's
Mongoose
70
Mongoose
•  Schema Validation
•  Casting
•  Business Logic Wrapper
•  http://mongoosejs.com/
Simple Mongoose
var mongoose = require('mongoose'), assert =
require('assert')
var Schema = mongoose.Schema;
//define a schema
var userSchema = new Schema({ name: String, age:
Number})
//create static members
userSchema.statics.findByName = function( name, cb){
return this.find( {"name": name}, cb);
}
…
Simple Mongoose
…
//generate a model
var User = mongoose.model('User', userSchema);
//initiate the new user, validates the given arguments
var u1 = User({name:"Many Delgado", age:14});
//just save it
u1.save(function(err){
assert.equal(null, err);
});
73
Other Projects
Project Repository
MongoSkin https://github.com/kissjs/node-mongoskin
Mongolia https://github.com/masylum/mongolia
Mongojs https://github.com/mafintosh/mongojs
MongoSmash https://github.com/bengl/mongosmash
MEAN Stack
75
MEAN Stack
•  MongoDB
•  Express.js
•  Angular JS
•  Node.js
Express is a minimal and flexible Node.js web
application framework that provides a robust
set of features for web and mobile
applications.
AngularJS lets you extend HTML vocabulary
for your application. The resulting
environment is extraordinarily expressive,
readable, and quick to develop
Building your first app with MongoDB: Creating
a RESTAPI using the MEAN Stack
https://www.mongodb.com/blog/post/building-
your-first-application-mongodb-creating-rest-
api-using-mean-stack-part-1
Meteor
Meteor is a complete open source platform for
building web and mobile apps in pure
JavaScript.
81
Meteor
•  Responsiveness
•  Reactiveness
•  Multiplatform
•  Unified Package System
•  Hot Deploys
https://www.meteor.com/try
METEOR: Build IOS andAndroidApps
that are a delight to use
http://www.mongodb.com/blog/post/meteor-
build-ios-and-android-apps-are-delight-use
Recap
84
What we talked about today…
•  Node.js is a very productive language
–  Our driver is highly adopted
–  Updated
–  Fully compatible
•  CRUD Operations
–  Insert, Update, Remove, Delete
•  Write Concerns
–  Flexible to write
•  Read Preferences
–  Flexible to read
•  Aggregation Framework
–  Analytics at your fingertips
85
Large Ecosystem
•  Mongoose
•  Mean Stack
•  Meteor
•  Many other projects
86
Where to next?
•  Questions on the driver:
–  https://groups.google.com/forum/#!forum/node-mongodb-native
•  Issues:
–  https://jira.mongodb.org/browse/NODE/?
selectedTab=com.atlassian.jira.jira-projects-plugin:summary-
panel
•  Tutorial:
–  http://mongodb.github.io/node-mongodb-native/2.0/
•  Todays code:
–  https://github.com/nleite/firstappnodejs
•  Other:
–  http://www.mongodb.com/norberto
87
For More Information
Resource Location
Case Studies mongodb.com/customers
Presentations mongodb.com/presentations
Free Online Training education.mongodb.com
Webinars and Events mongodb.com/events
Documentation docs.mongodb.org
MongoDB Downloads mongodb.com/download
Additional Info info@mongodb.com
Blog blog.mongodb.com
88
Register now: mongodbworld.com!
!
Use Code NorbertoLeite for additional 25% Off!
*Come as a group of 3 or more – Save another 25%!
http://cl.jroo.me/z3/v/D/C/e/a.baa-Too-many-bicycles-on-the-van.jpg
Questions?
@nleite
norberto@mongodb.com
http://www.mongodb.com/norberto
MongoDB and Node.js

More Related Content

What's hot (20)

PDF
Spring Framework - Core
Dzmitry Naskou
 
PDF
Express node js
Yashprit Singh
 
PPTX
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
PPTX
.Net Core
Bertrand Le Roy
 
PDF
Arquitetura Node com NestJS
Vanessa Me Tonini
 
PPTX
Node.Js: Basics Concepts and Introduction
Kanika Gera
 
PPTX
Introduction to NodeJS
Cere Labs Pvt. Ltd
 
PPTX
React state
Ducat
 
PPTX
MongoDB - Aggregation Pipeline
Jason Terpko
 
PPT
Maven Introduction
Sandeep Chawla
 
PDF
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
PPSX
Coding standard
FAROOK Samath
 
PPTX
Introduction to Node js
Akshay Mathur
 
PDF
Nodejs presentation
Arvind Devaraj
 
PPTX
What Is Express JS?
Simplilearn
 
PDF
Solid NodeJS with TypeScript, Jest & NestJS
Rafael Casuso Romate
 
PPTX
Node.js Express
Eyal Vardi
 
PPTX
Meetup angular http client
Gaurav Madaan
 
Spring Framework - Core
Dzmitry Naskou
 
Express node js
Yashprit Singh
 
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
TypeScript Introduction
Dmitry Sheiko
 
.Net Core
Bertrand Le Roy
 
Arquitetura Node com NestJS
Vanessa Me Tonini
 
Node.Js: Basics Concepts and Introduction
Kanika Gera
 
Introduction to NodeJS
Cere Labs Pvt. Ltd
 
React state
Ducat
 
MongoDB - Aggregation Pipeline
Jason Terpko
 
Maven Introduction
Sandeep Chawla
 
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Coding standard
FAROOK Samath
 
Introduction to Node js
Akshay Mathur
 
Nodejs presentation
Arvind Devaraj
 
What Is Express JS?
Simplilearn
 
Solid NodeJS with TypeScript, Jest & NestJS
Rafael Casuso Romate
 
Node.js Express
Eyal Vardi
 
Meetup angular http client
Gaurav Madaan
 

Viewers also liked (20)

PPTX
harry presentation
thembhani mapengo
 
PDF
How To Get Hadoop App Intelligence with Driven
Cascading
 
PDF
OPENEXPO Madrid 2015 - Advanced Applications with MongoDB
MongoDB
 
PPTX
Advanced applications with MongoDB
Norberto Leite
 
PPTX
Data Distribution Theory
William LaForest
 
PDF
Advanced MongoDB Aggregation Pipelines
Tom Schreiber
 
PDF
Analyse Yourself
Norberto Leite
 
PPTX
Data Treatment MongoDB
Norberto Leite
 
PPTX
MongoDB + Spring
Norberto Leite
 
PDF
MongoDB and Python
Norberto Leite
 
PDF
Geospatial and MongoDB
Norberto Leite
 
PPTX
MongoDB on Financial Services Sector
Norberto Leite
 
PDF
Building Killer RESTful APIs with NodeJs
Srdjan Strbanovic
 
KEY
Dcjq node.js presentation
async_io
 
PDF
MongoDB Certification Study Group - May 2016
Norberto Leite
 
PPTX
From Monolithic to Microservices in 45 Minutes
MongoDB
 
KEY
Getting Started with MongoDB and Node.js
Grant Goodale
 
PDF
How Financial Services Organizations Use MongoDB
MongoDB
 
PDF
Introduction to Nodejs
Gabriele Lana
 
PPTX
Introduction to Node.js
Vikash Singh
 
harry presentation
thembhani mapengo
 
How To Get Hadoop App Intelligence with Driven
Cascading
 
OPENEXPO Madrid 2015 - Advanced Applications with MongoDB
MongoDB
 
Advanced applications with MongoDB
Norberto Leite
 
Data Distribution Theory
William LaForest
 
Advanced MongoDB Aggregation Pipelines
Tom Schreiber
 
Analyse Yourself
Norberto Leite
 
Data Treatment MongoDB
Norberto Leite
 
MongoDB + Spring
Norberto Leite
 
MongoDB and Python
Norberto Leite
 
Geospatial and MongoDB
Norberto Leite
 
MongoDB on Financial Services Sector
Norberto Leite
 
Building Killer RESTful APIs with NodeJs
Srdjan Strbanovic
 
Dcjq node.js presentation
async_io
 
MongoDB Certification Study Group - May 2016
Norberto Leite
 
From Monolithic to Microservices in 45 Minutes
MongoDB
 
Getting Started with MongoDB and Node.js
Grant Goodale
 
How Financial Services Organizations Use MongoDB
MongoDB
 
Introduction to Nodejs
Gabriele Lana
 
Introduction to Node.js
Vikash Singh
 
Ad

Similar to MongoDB and Node.js (20)

PPTX
Webinar: Building Your First App in Node.js
MongoDB
 
PPTX
Webinar: Building Your First App in Node.js
MongoDB
 
PDF
Java Persistence Frameworks for MongoDB
MongoDB
 
PDF
Parse cloud code
維佋 唐
 
KEY
Rails with mongodb
Kosuke Matsuda
 
PDF
MeaNstack on Docker
Daniel Ku
 
PDF
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB
 
PDF
Practical Chef and Capistrano for Your Rails App
SmartLogic
 
PPTX
Introduction to MongoDB
Chun-Kai Wang
 
KEY
Practical Use of MongoDB for Node.js
async_io
 
PDF
How To Build and Run Node Apps with Docker and Compose
Docker, Inc.
 
PDF
Mongodb
Scott Motte
 
PPTX
Get expertise with mongo db
Amit Thakkar
 
PDF
From development environments to production deployments with Docker, Compose,...
Jérôme Petazzoni
 
PPTX
Java Persistence Frameworks for MongoDB
Tobias Trelle
 
PDF
오픈 소스 프로그래밍 - NoSQL with Python
Ian Choi
 
ODP
Introduction to MongoDB with PHP
fwso
 
PPTX
Rails Engine | Modular application
mirrec
 
PDF
Puppet at Opera Sofware - PuppetCamp Oslo 2013
Cosimo Streppone
 
PPTX
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
Tobias Trelle
 
Webinar: Building Your First App in Node.js
MongoDB
 
Webinar: Building Your First App in Node.js
MongoDB
 
Java Persistence Frameworks for MongoDB
MongoDB
 
Parse cloud code
維佋 唐
 
Rails with mongodb
Kosuke Matsuda
 
MeaNstack on Docker
Daniel Ku
 
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB
 
Practical Chef and Capistrano for Your Rails App
SmartLogic
 
Introduction to MongoDB
Chun-Kai Wang
 
Practical Use of MongoDB for Node.js
async_io
 
How To Build and Run Node Apps with Docker and Compose
Docker, Inc.
 
Mongodb
Scott Motte
 
Get expertise with mongo db
Amit Thakkar
 
From development environments to production deployments with Docker, Compose,...
Jérôme Petazzoni
 
Java Persistence Frameworks for MongoDB
Tobias Trelle
 
오픈 소스 프로그래밍 - NoSQL with Python
Ian Choi
 
Introduction to MongoDB with PHP
fwso
 
Rails Engine | Modular application
mirrec
 
Puppet at Opera Sofware - PuppetCamp Oslo 2013
Cosimo Streppone
 
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
Tobias Trelle
 
Ad

More from Norberto Leite (20)

PDF
Data Modelling for MongoDB - MongoDB.local Tel Aviv
Norberto Leite
 
PPTX
Avoid Query Pitfalls
Norberto Leite
 
PPTX
MongoDB and Spark
Norberto Leite
 
PDF
Mongo db 3.4 Overview
Norberto Leite
 
PDF
MongodB Internals
Norberto Leite
 
PDF
MongoDB WiredTiger Internals
Norberto Leite
 
PDF
MongoDB 3.2 Feature Preview
Norberto Leite
 
PDF
Mongodb Spring
Norberto Leite
 
PDF
MongoDB on Azure
Norberto Leite
 
PDF
MongoDB: Agile Combustion Engine
Norberto Leite
 
PDF
MongoDB Capacity Planning
Norberto Leite
 
PDF
Spark and MongoDB
Norberto Leite
 
PDF
Python and MongoDB
Norberto Leite
 
PDF
Strongly Typed Languages and Flexible Schemas
Norberto Leite
 
PDF
Effectively Deploying MongoDB on AEM
Norberto Leite
 
PPTX
MongoDB Ops Manager
Norberto Leite
 
PDF
Let the Tiger Roar - MongoDB 3.0
Norberto Leite
 
PPTX
MongoDB + Java - Everything you need to know
Norberto Leite
 
PPTX
MongoDB Capacity Planning
Norberto Leite
 
PDF
Building your first app with MongoDB
Norberto Leite
 
Data Modelling for MongoDB - MongoDB.local Tel Aviv
Norberto Leite
 
Avoid Query Pitfalls
Norberto Leite
 
MongoDB and Spark
Norberto Leite
 
Mongo db 3.4 Overview
Norberto Leite
 
MongodB Internals
Norberto Leite
 
MongoDB WiredTiger Internals
Norberto Leite
 
MongoDB 3.2 Feature Preview
Norberto Leite
 
Mongodb Spring
Norberto Leite
 
MongoDB on Azure
Norberto Leite
 
MongoDB: Agile Combustion Engine
Norberto Leite
 
MongoDB Capacity Planning
Norberto Leite
 
Spark and MongoDB
Norberto Leite
 
Python and MongoDB
Norberto Leite
 
Strongly Typed Languages and Flexible Schemas
Norberto Leite
 
Effectively Deploying MongoDB on AEM
Norberto Leite
 
MongoDB Ops Manager
Norberto Leite
 
Let the Tiger Roar - MongoDB 3.0
Norberto Leite
 
MongoDB + Java - Everything you need to know
Norberto Leite
 
MongoDB Capacity Planning
Norberto Leite
 
Building your first app with MongoDB
Norberto Leite
 

Recently uploaded (20)

PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Tally software_Introduction_Presentation
AditiBansal54083
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 

MongoDB and Node.js

  • 1. MongoDB + Node.js Building first app with MongoDB and Node.js
  • 3. 3 Ola, I'm Norberto! Norberto Leite Technical Evangelist Madrid, Spain @nleite [email protected] http://www.mongodb.com/norberto
  • 7. 7 Few reasons why Flexible Agile Web Language
  • 8. 8 MongoDB + Javascript •  MongoDB Shell –  JS interperter •  MongoDB MapReduce –  Runs on top of V8 –  Map and Reduce functions are JS functions •  Native support for Node.js –  One of the most used Drivers out there! –  https://www.npmjs.com/package/mongodb
  • 11. 11 2 Foundations •  Events / Event Loop –  Single Thread Applications –  No threads –  Events Emitter –  Event Queue –  Known Events •  Streams –  Read, Write, Both –  Unix Pipes –  We use it extensively!
  • 13. npm package $ npm install mongodb
  • 17. package.json file $ mkdir firstappnodejs $ cd firstappnodejs $ npm init
  • 18. package.json file $ mkdir firstappnodejs $ cd firstappnodejs $ npm init ... { "name": "firstappnodejs", "version": "0.0.1", "description": "Small demo webinar application", "main": "index.js", "scripts": { "test": "workitout" }, "repository": { "type": "git", "url": "git://github.com/nleite/firstappnodejs" }, "dependencies": { "mongodb": "~2.0" }, "keywords": [http://docs.mongodb.org/ecosystem/drivers/node-js/#compatibility "demo", "nodejs", "mongodb" ], "author": "Norberto Leite", "license": "Apache 2.0", "bugs": { "url": "https://github.com/nleite/firstappnodejs/issues" }, "homepage": "https://github.com/nleite/firstappnodejs"
  • 19. package.json file $ mkdir firstappnodejs $ cd firstappnodejs $ npm init ... { "name": "firstappnodejs", "version": "0.0.1", "description": "Small demo webinar application", "main": "index.js", "scripts": { "test": "workitout" }, "repository": { "type": "git", "url": "git://github.com/nleite/firstappnodejs" }, "dependencies": { "mongodb": "~2.0" }, "keywords": [ "demo", "nodejs", "mongodb" ], "author": "Norberto Leite", "license": "Apache 2.0", "bugs": { "url": "https://github.com/nleite/firstappnodejs/issues" }, "homepage": "https://github.com/nleite/firstappnodejs"
  • 20. Install our new firstappnodejs app! $ npm install > [email protected] install … … > [email protected] install > [email protected] node_modules/mongodb ├── [email protected] ([email protected], [email protected], [email protected], [email protected]) └── [email protected] ([email protected], [email protected]) firstappnodejs/ $ ls node_modules package.json
  • 22. boot up MongoDB Server $ mkdir ~/firstappdb $ mongod --dbpath ~/firstappdb
  • 23. boot up MongoDB Server $ mkdir ~/firstappdb $ mongod --dbpath ~/firstappdb --auth --keyfile ~/n.pem https://www.mongodb.com/products/mongodb-enterprise-advanced
  • 24. boot up MongoDB Server $ mkdir ~/firstappdb $ mongod --dbpath ~/firstappdb --auth --keyfile ~/n.pem https://www.mongodb.com/products/mongodb-enterprise-advanced
  • 25. var MongoClient = require('mongodb').MongoClient, assert = require('assert'); Connect
  • 26. var MongoClient = require('mongodb').MongoClient, assert = require('assert'); //connection uri var uri = "mongodb://localhost:27017/firstapp" Connect
  • 27. var MongoClient = require('mongodb').MongoClient, assert = require('assert'); //connection uri var uri = "mongodb://localhost:27017/firstapp" //connect to MongoDB MongoClient.connect(uri, function(err, db){ assert.equal(null, err); console.log("Connected correctly to server"); db.close(); }); Connect
  • 28. 28 Connection Pooling •  No traditional Pooling mechanism –  Single thread process •  Sockets to pipeline operations •  Failover –  Buffering up operations –  bufferMaxEntries –  numberOfRetries –  retryMiliSeconds http://mongodb.github.io/node-mongodb-native/2.0/api/Db.html
  • 29. CRUD
  • 30. var insertDocuments = function(db, cb){ //we don't need to explicitly create a collection var collection = db.collection('myCollection'); collection.insertMany([ {"mongodb": "is just awesome"}, {"nodejs": "so awesome"} ], function(err, result){ assert.equal(null, err); //inserted 2 documents assert.equal(2, result.insertedCount); //invoke callback cb(result); }); } Insert http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
  • 31. var insertDocuments = function(db, cb){ //we don't need to explicitly create a collection var collection = db.collection('myCollection'); collection.insertMany([ {"mongodb": "is just awesome"}, {"nodejs": "so awesome"} ], function(err, result){ assert.equal(null, err); //inserted 2 documents assert.equal(2, result.insertedCount); //invoke callback cb(result); }); } Insert http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
  • 32. var insertDocuments = function(db, cb){ //we don't need to explicitly create a collection var collection = db.collection('myCollection'); collection.insertMany([ {"mongodb": "is just awesome"}, {"nodejs": "so awesome"} ], function(err, result){ assert.equal(null, err); //inserted 2 documents assert.equal(2, result.insertedCount); //invoke callback cb(result); }); } Insert http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
  • 33. var insertDocuments = function(db, cb){ //we don't need to explicitly create a collection var collection = db.collection('myCollection'); collection.insertMany([ {"mongodb": "is just awesome"}, {"nodejs": "so awesome"} ], function(err, result){ assert.equal(null, err); //inserted 2 documents assert.equal(2, result.insertedCount); //invoke callback cb(result); }); } Insert http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
  • 34. MongoClient.connect(uri, function(err, db) { assert.equal(null, err); console.log("Sweet! Talking to Server"); insertDocuments(db, function() { db.close(); }); }); Insert http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
  • 35. MongoClient.connect(uri, function(err, db) { assert.equal(null, err); console.log("Sweet! Talking to Server"); insertDocuments(db, function() { db.close(); }); }); Insert http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
  • 36. var updateDocument = function(db, cb){ var collection = db.collection("myCollection"); collection.updateOne( {"mongodb": "is just awesome"}, {$set: {"users": ["nleite"]}}, function( err, result){ assert.equal(null, err); assert.equal(1, result.modifiedCount); console.log("Cool, just updated"); cb(result); }); } Update http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
  • 37. var updateDocument = function(db, cb){ var collection = db.collection("myCollection"); collection.updateOne( {"mongodb": "is just awesome"}, {$set: {"users": ["nleite"]}}, function( err, result){ assert.equal(null, err); assert.equal(1, result.modifiedCount); console.log("Cool, just updated"); cb(result); }); } Update http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
  • 38. var updateDocument = function(db, cb){ var collection = db.collection("myCollection"); collection.updateOne( {"mongodb": "is just awesome"}, {$set: {"users": ["nleite"]}}, function( err, result){ assert.equal(null, err); assert.equal(1, result.modifiedCount); console.log("Cool, just updated"); cb(result); }); } Update http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
  • 39. var updateDocument = function(db, cb){ var collection = db.collection("myCollection"); collection.updateOne( {"mongodb": "is just awesome"}, {$set: {"users": ["nleite"]}}, function( err, result){ assert.equal(null, err); assert.equal(1, result.modifiedCount); console.log("Cool, just updated"); cb(result); }); } Update http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
  • 40. MongoClient.connect(uri, function(err, db) { assert.equal(null, err); console.log("Ok, I can now update!"); updateDocuments(db, function() { db.close(); }); }); Update http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
  • 41. Remove var removeDocument = function(db, cb){ var collection = db.collection("myCollection"); collection.deleteOne( {"users": "nleite"}, function( err, result){ assert.equal(null, err); assert.equal(1, result.deletedCount); console.log("purged the @nleite contaminated data!"); cb(result); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove
  • 42. Remove var removeDocument = function(db, cb){ var collection = db.collection("myCollection"); collection.deleteOne( {"users": "nleite"}, function( err, result){ assert.equal(null, err); assert.equal(1, result.deletedCount); console.log("purged the @nleite contaminated data!"); cb(result); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove
  • 43. Remove var removeDocument = function(db, cb){ var collection = db.collection("myCollection"); collection.deleteOne( {"users": "nleite"}, function( err, result){ assert.equal(null, err); assert.equal(1, result.deletedCount); console.log("purged the @nleite contaminated data!"); cb(result); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove
  • 44. Remove MongoClient.connect(uri, function(err, db) { assert.equal(null, err); console.log("Ok, I can now delete!"); removeDocuments(db, function() { db.close(); }); }); http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove
  • 45. Find var findAllDocuments = function(db, cb){ var collection = db.collection('myDocuments'); //or collection.find() collection.find({}).toArray(function(err, docs){ assert.equal(err, null); assert.equal(1, docs.length); console.log("Gotcha! found "+ docs.length); console.dir(docs); cb(docs); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#find
  • 46. Find var findAllDocuments = function(db, cb){ var collection = db.collection('myDocuments'); //or collection.find() collection.find({}).toArray(function(err, docs){ assert.equal(err, null); assert.equal(1, docs.length); console.log("Gotcha! found "+ docs.length); console.dir(docs); cb(docs); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#find
  • 47. Find var findAllDocuments = function(db, cb){ var collection = db.collection('myDocuments'); //or collection.find() collection.find({}).toArray(function(err, docs){ assert.equal(err, null); assert.equal(1, docs.length); console.log("Gotcha! found "+ docs.length); console.dir(docs); cb(docs); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#find
  • 50. Different Schemas var insertDifferentShapes = function(db, cb){ var doc1 = {"name": "Norberto", "talks": [ {"nodejs":10}, {"java":15}, "python":11]}; var doc2 = {"name": "Bryan", "webinars": 30}; var coll = db.collection("content") coll.insertMany( [doc1, doc2], function(err, result){ assert.equal(err, null); assert.equal(2, result.insertedCount); console.log("Sweet, inserted "+ result.insertedCount); cb(result); }); } http://docs.mongodb.org/manual/data-modeling/
  • 51. Different Schemas var insertDifferentShapes = function(db, cb){ var doc1 = {"name": "Norberto", "talks": [ {"nodejs":10}, {"java":15}, "python":11]}; var doc2 = {"name": "Bryan", "webinars": 30}; var coll = db.collection("content") coll.insertMany( [doc1, doc2], function(err, result){ assert.equal(err, null); assert.equal(2, result.insertedCount); console.log("Sweet, inserted "+ result.insertedCount); cb(result); }); } http://docs.mongodb.org/manual/data-modeling/
  • 56. Different WriteConcerns var insertSuperImportant = function(db, cb){ var customer = {"name": "Manny Delgado", "age": 14}; var coll = db.collection("customers"); var writeConcern = {"w": "majority"}; col.insertOne( customer, writeConcern, function(err, result){ assert.equal(err, null); assert.equal(1, result.insertedCount); console.log("Inserted super important record"); cb(result); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/WriteConcernError.html
  • 57. Different WriteConcerns var insertSuperImportant = function(db, cb){ var customer = {"name": "Manny Delgado", "age": 14}; var coll = db.collection("customers"); var writeConcern = {"w": "majority"}; col.insertOne( customer, writeConcern, function(err, result){ assert.equal(err, null); assert.equal(1, result.insertedCount); console.log("Inserted super important record"); cb(result); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/WriteConcernError.html
  • 59. 59 Read Preference •  Read from Primary (default) ReadPreference.PRIMARY •  Read from Primary Preferably ReadPreference.PRIMARY_PREFERRED •  Read from Secondary ReadPreference.SECONDARY •  Read from Secondary Preferably ReadPreference.SECONDARY_PREFERRED •  Read from Nearest Node ReadPreference.NEAREST http://mongodb.github.io/node-mongodb-native/2.0/api/ReadPreference.html
  • 60. Read From Nearest var readNearestWaterMelonColor = function(db, cb){ var rp = ReadPreference.NEAREST; var coll = db.collection("products", {ReadPreference:rp}); var query = {"color": "water melon green"}; collection.find(query).toArray(function(err, docs){ assert.equal(err, null); assert.equal(1, docs.length); console.log("So many products: "+ docs.length); console.dir(docs); cb(docs); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/ReadPreference.html
  • 61. Read From Nearest var readNearestWaterMelonColor = function(db, cb){ var rp = ReadPreference.NEAREST; var coll = db.collection("products", {ReadPreference:rp}); var query = {"color": "water melon green"}; collection.find(query).toArray(function(err, docs){ assert.equal(err, null); assert.equal(1, docs.length); console.log("So many products: "+ docs.length); console.dir(docs); cb(docs); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/ReadPreference.html
  • 62. Read From Nearest var readNearestWaterMelonColor = function(db, cb){ var rp = ReadPreference.NEAREST; var coll = db.collection("products", {readPreference:rp}); var query = {"color": "water melon green"}; collection.find(query).toArray(function(err, docs){ assert.equal(err, null); assert.equal(1, docs.length); console.log("So many products: "+ docs.length); console.dir(docs); cb(docs); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/ReadPreference.html
  • 64. Aggregation var aggregateAvgAgeGender = function( db, cb){ //{age:XX, name:"user name", gender: "M/F"} var pipeline = [ {$group: { "_id": "$gender", avg_age: {$avg: "$age"}}}, ]; var coll = db.collection("users"); var cursor = coll.aggregate(pipeline); cursor.forEach( function(x){ console.log("Gender " + x._id + " age average " + x.avg_age) }, function(x) { cb(cursor); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#aggregate
  • 65. Aggregation var aggregateAvgAgeGender = function( db, cb){ //{age:XX, name:"user name", gender: "M/F"} var pipeline = [ {$group: { "_id": "$gender", avg_age: {$avg: "$age"}}}, ]; var coll = db.collection("users"); var cursor = coll.aggregate(pipeline); cursor.forEach( function(x){ console.log("Gender " + x._id + " age average " + x.avg_age) }, function(x) { cb(cursor); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#aggregate
  • 66. Aggregation var aggregateAvgAgeGender = function( db, cb){ //{age:XX, name:"user name", gender: "M/F"} var pipeline = [ {$group: { "_id": "$gender", avg_age: {$avg: "$age"}}}, ]; var coll = db.collection("users"); var cursor = coll.aggregate(pipeline); cursor.forEach( function(x){ console.log("Gender " + x._id + " age average " + x.avg_age) }, function(x) { cb(cursor); }); } http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#aggregate
  • 67. Aggregation var aggregateAvgAgeGender = function( db, cb){ //{age:XX, name:"user name", gender: "M/F"} var pipeline = [ {$match:{"age": $gt: 18}}, {$group: { "_id": "$gender", avg_age: {$avg: "$age"}}}, {$project:{"ID": "$_id", "average": "$avg_age" }} ]; var cursor = coll.aggregate(pipeline); var coll = db.collection("users"); cursor.forEach( function(x){ console.log("Gender " + x._id + " age average " + x.avg_age) }, function(x) { cb(cursor); });} http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#aggregate
  • 68. ODM's
  • 70. 70 Mongoose •  Schema Validation •  Casting •  Business Logic Wrapper •  http://mongoosejs.com/
  • 71. Simple Mongoose var mongoose = require('mongoose'), assert = require('assert') var Schema = mongoose.Schema; //define a schema var userSchema = new Schema({ name: String, age: Number}) //create static members userSchema.statics.findByName = function( name, cb){ return this.find( {"name": name}, cb); } …
  • 72. Simple Mongoose … //generate a model var User = mongoose.model('User', userSchema); //initiate the new user, validates the given arguments var u1 = User({name:"Many Delgado", age:14}); //just save it u1.save(function(err){ assert.equal(null, err); });
  • 73. 73 Other Projects Project Repository MongoSkin https://github.com/kissjs/node-mongoskin Mongolia https://github.com/masylum/mongolia Mongojs https://github.com/mafintosh/mongojs MongoSmash https://github.com/bengl/mongosmash
  • 75. 75 MEAN Stack •  MongoDB •  Express.js •  Angular JS •  Node.js
  • 76. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
  • 77. AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop
  • 78. Building your first app with MongoDB: Creating a RESTAPI using the MEAN Stack https://www.mongodb.com/blog/post/building- your-first-application-mongodb-creating-rest- api-using-mean-stack-part-1
  • 80. Meteor is a complete open source platform for building web and mobile apps in pure JavaScript.
  • 81. 81 Meteor •  Responsiveness •  Reactiveness •  Multiplatform •  Unified Package System •  Hot Deploys https://www.meteor.com/try
  • 82. METEOR: Build IOS andAndroidApps that are a delight to use http://www.mongodb.com/blog/post/meteor- build-ios-and-android-apps-are-delight-use
  • 83. Recap
  • 84. 84 What we talked about today… •  Node.js is a very productive language –  Our driver is highly adopted –  Updated –  Fully compatible •  CRUD Operations –  Insert, Update, Remove, Delete •  Write Concerns –  Flexible to write •  Read Preferences –  Flexible to read •  Aggregation Framework –  Analytics at your fingertips
  • 85. 85 Large Ecosystem •  Mongoose •  Mean Stack •  Meteor •  Many other projects
  • 86. 86 Where to next? •  Questions on the driver: –  https://groups.google.com/forum/#!forum/node-mongodb-native •  Issues: –  https://jira.mongodb.org/browse/NODE/? selectedTab=com.atlassian.jira.jira-projects-plugin:summary- panel •  Tutorial: –  http://mongodb.github.io/node-mongodb-native/2.0/ •  Todays code: –  https://github.com/nleite/firstappnodejs •  Other: –  http://www.mongodb.com/norberto
  • 87. 87 For More Information Resource Location Case Studies mongodb.com/customers Presentations mongodb.com/presentations Free Online Training education.mongodb.com Webinars and Events mongodb.com/events Documentation docs.mongodb.org MongoDB Downloads mongodb.com/download Additional Info [email protected] Blog blog.mongodb.com
  • 88. 88 Register now: mongodbworld.com! ! Use Code NorbertoLeite for additional 25% Off! *Come as a group of 3 or more – Save another 25%!