SlideShare a Scribd company logo
1 of 10
Download to read offline
Node.js with Mongo(ose)
Gergely Nemeth
What is MongoDB?
Gergely Nemeth
● document-oriented database (NoSQL)
● ad hoc queries
● indexing (any field)
● replication, sharding, load balancing
● aggregation/mapreduce
● javascript execution (V8)
● HTTP interface
Up and running with Mongo
Gergely Nemeth
1. download from: http://www.mongodb.org/downloads
2. start a mongod instance with: mongod
3. connect to mongod with: mongo
4. let’s get rolling ;)
Basic queries
Gergely Nemeth
● use testDb;
● db.testDb.insert({co:’apple’, cnt: 3});
● db.testDb.insert({co:’lmi’, cnt: 1});
● db.testDb.find();
● db.testDb.findOne();
● db.testDb.find().limit(2);
● db.testDb.find().sort({cnt:1});
Mongoose
Gergely Nemeth
● mongodb object modeling for node.js
● schema-based
npm install mongoose
//app.js
var mongoose = require('mongoose'); mongoose.connect('mongodb:
//localhost/test');
var myFirstSchema = mongoose.Schema({ name: String });
var myFirstSchema = mongoose.model('myFirstSchema', myFirstSchema);
var myFirstSchemaObject = new myFirstSchema({ name: 'mongo' });
myFirstSchemaObject.save(function(err){/*error handling*/});
myFirstSchema.find(function (err, results) {
if (err) // TODO handle err
console.log(results)
})
Populate
Gergely Nemeth
● populates document references
● MongoDB doesn’t have ‘Populate’, it comes from
Mongoose, so additional queries will be ran in the
background
Page.findOne({name:’My little pony’})
.populate(‘author’)
.exec(function(err, data) {
console.log(data)
})
Aggregation
Gergely Nemeth
● available since version 2.2
● unix-like pipelines for: $project, $match, $limit, $skip,
$unwind, $group, $sort, $geoNear
User.aggregate([
{ $match: {someBoolVal: true} },
{ $limit : 10 },
{ $project: {
fid: "$fid"
}},
], function(err, data) {
}
);
Aggregation advices
Gergely Nemeth
● $match as soon as possible
● operators $match, $sort, $limit, $skip can
take advantage of indexes, so use them!
● aggregations works well with sharded configurations
● if an aggregation operations uses more than 10% of
SYS RAM, it will produce an error
● output of an agg. operation cannot be bigger than
16MB, if does, it will produce an error
MapReduce
Gergely Nemeth
● Map(): sorting and filtering
● Reduce(): summary operation
● in Mongo Map and Reduce are both JavaScript
functions (ran by V8)
var o = {};
o.map = function () { emit(this.name, 1) }
o.reduce = function (k, vals) { return vals.length }
User.mapReduce(o, function (err, results) {
console.log(results)
})
$where
Gergely Nemeth
● use only when all hell breaks loose, and the query
cannot be express with other operators
● cannot take advantage of indexes!
● requires a table scan!
db.myCollection.find( "this.credits == this.debits
|| this.credits > this.debits" );

More Related Content

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 

Node.js with mongo(ose)

  • 2. What is MongoDB? Gergely Nemeth ● document-oriented database (NoSQL) ● ad hoc queries ● indexing (any field) ● replication, sharding, load balancing ● aggregation/mapreduce ● javascript execution (V8) ● HTTP interface
  • 3. Up and running with Mongo Gergely Nemeth 1. download from: http://www.mongodb.org/downloads 2. start a mongod instance with: mongod 3. connect to mongod with: mongo 4. let’s get rolling ;)
  • 4. Basic queries Gergely Nemeth ● use testDb; ● db.testDb.insert({co:’apple’, cnt: 3}); ● db.testDb.insert({co:’lmi’, cnt: 1}); ● db.testDb.find(); ● db.testDb.findOne(); ● db.testDb.find().limit(2); ● db.testDb.find().sort({cnt:1});
  • 5. Mongoose Gergely Nemeth ● mongodb object modeling for node.js ● schema-based npm install mongoose //app.js var mongoose = require('mongoose'); mongoose.connect('mongodb: //localhost/test'); var myFirstSchema = mongoose.Schema({ name: String }); var myFirstSchema = mongoose.model('myFirstSchema', myFirstSchema); var myFirstSchemaObject = new myFirstSchema({ name: 'mongo' }); myFirstSchemaObject.save(function(err){/*error handling*/}); myFirstSchema.find(function (err, results) { if (err) // TODO handle err console.log(results) })
  • 6. Populate Gergely Nemeth ● populates document references ● MongoDB doesn’t have ‘Populate’, it comes from Mongoose, so additional queries will be ran in the background Page.findOne({name:’My little pony’}) .populate(‘author’) .exec(function(err, data) { console.log(data) })
  • 7. Aggregation Gergely Nemeth ● available since version 2.2 ● unix-like pipelines for: $project, $match, $limit, $skip, $unwind, $group, $sort, $geoNear User.aggregate([ { $match: {someBoolVal: true} }, { $limit : 10 }, { $project: { fid: "$fid" }}, ], function(err, data) { } );
  • 8. Aggregation advices Gergely Nemeth ● $match as soon as possible ● operators $match, $sort, $limit, $skip can take advantage of indexes, so use them! ● aggregations works well with sharded configurations ● if an aggregation operations uses more than 10% of SYS RAM, it will produce an error ● output of an agg. operation cannot be bigger than 16MB, if does, it will produce an error
  • 9. MapReduce Gergely Nemeth ● Map(): sorting and filtering ● Reduce(): summary operation ● in Mongo Map and Reduce are both JavaScript functions (ran by V8) var o = {}; o.map = function () { emit(this.name, 1) } o.reduce = function (k, vals) { return vals.length } User.mapReduce(o, function (err, results) { console.log(results) })
  • 10. $where Gergely Nemeth ● use only when all hell breaks loose, and the query cannot be express with other operators ● cannot take advantage of indexes! ● requires a table scan! db.myCollection.find( "this.credits == this.debits || this.credits > this.debits" );