4. What is MongoDB?
Scalable High-Performance Open-source, Document-orientated database.
◦ Built for Speed
◦ Rich Document based queries for Easy readability.
◦ Full Index Support for High Performance.
◦ Replication and Failover for High Availability.
◦ Auto Sharding for Easy Scalability.
◦ Map / Reduce for Aggregation.
4
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
5. Why use MongoDB
◦ SQL was invented in the 70’s to store data.
◦ MongoDB stores documents (or) objects.
◦ Now-a-days, everyone works with objects (Python/Ruby/Java/etc.)
◦ And we need Databases to persist our objects. Then why not store objects directly?
◦ Embedded documents and arrays reduce need for joins. No Joins and No-multi
document transactions.
5
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
6. What is MongoDB great for?
◦ RDBMS replacement for Web Applications.
◦ Semi-structured Content Management.
◦ Real-time Analytics & High-Speed Logging
◦ Caching and High Scalability
Web 2.0, Media, SAAS, Gaming
HealthCare, Finance, Telecom, Government
6
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
7. Not great for?
◦ Highly Transactional Applications.
◦ Problems requiring SQL.
Some Companies using MongoDB in Production
7
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
8. Features
Simple Queries
◦ 簡單的查詢語句,沒有 join 操作
Document-based data model
◦ 資料使用 BSON (Binary JSON) 儲存
Sharding
◦ 提供 auto-sharding 實現資料的擴展性
GridFS
◦ MongoDB 的提供的文件儲存 API
MultiKeys
◦ 可以對 document 的某個數組屬性建立索引
MapReduce
◦ 可以用於進行複雜的統計和平行計算
Better Performance
◦ 使用 mmap 和定時 fsync 的方法,避免頻繁
I/O,使其性能更高
8
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
9. Terminology
RDBMS MongoDB
Database Database
Table Collection
Record/Row Document
Column Field
Primary Key _id
Foreign Key
9
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
14. Install MongoDB on Amazon EC2 (1/2)
About EC2
◦ EC2 is a Linux box
◦ Install MongoDB on EC2 is like install it on any Linux
Our installation
◦ We’ve installed MongoDB on EC2, with Ubuntu Linux Distribution
◦ It’s easy to setup EC2 instance, with few clicks on AWS console
◦ Following official instruction from MongoDB http://docs.mongodb.org/manual/tutorial/install-
mongodb-on-ubuntu/
◦ After this, you should be able to interact MongoDB with its console
14
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
15. Install MongoDB on Amazon EC2 (2/2)
Launch EC2 instance
◦ Remember to add your RSA public key for login into your AWS account before proceed
◦ Choose machine image (We have tested Ubuntu)
◦ Select instance type (spec), detail configurations and add storage(can leave them),
◦ Configure Security group (firewall, it allows ssh connection by default)
◦ Launch
MongoDB installation (Install binary from repository)
◦ Details are described in the link provided in the last slide
◦ Add GPG key for repo
◦ Add list for MongoDB.org repo
◦ Install it by apt
◦ Start service
◦ Use “mongo” to launch console and interact with it
15
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
16. Tool for Monitoring MongoDB
Mongo Management Service (MMS)
◦ https://mms.mongodb.com/
◦ Provision
◦ Any topology, at scale.
◦ Upgrade
◦ In minutes, with no downtime.
◦ Scale
◦ Add capacity, without taking your application offline.
◦ Continuous Backup
◦ Customize to meet your recovery goals.
◦ Point-in-time Recovery
◦ Restore to any point in time, because disasters aren't scheduled.
◦ Performance Alerts
◦ Monitor 100+ system metrics and get custom alerts before your system degrades.
16
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
17. Alternative Solutions for Installing MongoDB
MongoLab
◦ https://mongolab.com/
◦ Instead of install EC2 manually, it’s a PaaS delivers MongoDB service.
◦ Can deploy on AWS, Azure, Rackspace…etc
Amazon DynamoDB
◦ http://aws.amazon.com/dynamodb/
◦ Amazon DynamoDB is a fast and flexible NoSQL database service for all applications that need
consistent, single-digit millisecond latency at any scale.
17
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
23. Query Documents (1/4)
Select All Documents in a Collection
Equivalent to the previous operation
23
db.inventory.find( {} )
// SELECT * FROM inventory
db.inventory.find()
// SELECT * FROM inventory
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
24. Query Documents (2/4)
Specify Equality Condition
Specify Conditions Using Query Operators
24
db.inventory.find( { type: "snacks" } )
// SELECT * FROM inventory WHERE type = 'snacks'
db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )
// SELECT * FROM inventory WHERE type IN ('food', 'snacks')
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
25. Query Documents (3/4)
Specify AND Conditions
Specify OR Conditions
25
db.inventory.find( { type: 'food', price: { $lt: 9.95 } } )
// SELECT * FROM inventory WHERE type = 'food' AND price < 9.95
db.inventory.find(
{
$or: [ { qty: { $gt: 100 } }, { price: { $lt: 9.95 } } ]
}
)
// SELECT * FROM inventory WHERE qty > 100 OR price < 9.95
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
26. Query Documents (4/4)
Specify AND as well as OR Conditions
Query and Projection Operators
http://docs.mongodb.org/manual/reference/operator/query/
26
db.inventory.find(
{
type: 'food',
$or: [ { qty: { $gt: 100 } }, { price: { $lt: 9.95 } } ]
}
)
// SELECT * FROM inventory WHERE type = 'food' AND qty > 100 OR price < 9.95
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
27. Modify Documents (1/2)
Update Specific Fields in a Document
27
db.inventory.update(
{ item: "MNO2" },
{
$set: {
category: "apparel",
details: { model: "14Q3", manufacturer: "XYZ Company" }
},
$currentDate: { lastModified: true }
}
)
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
29. Remove Documents
Remove All Documents
Remove Documents that Match a Condition
Remove a Single Document that Matches a Condition
29
db.inventory.remove({})
db.inventory.remove( { type : "food" } )
db.inventory.remove( { type : "food" }, 1 )
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
31. RESTful API Implementation
31
實驗
◦ 使用 MongoDB 作為後端資料庫
◦ 設計 REST 風格的 API 對應資料庫的新增、讀取、修改、刪除之操作
◦ 透過 API 建立一個簡易的 Blog 應用程式
HTTP verb URL Action
GET /api/article Display all articles
GET /api/article/{id} Display an article by id
POST /api/article Create an article
PUT /api/article/{id} Update an article by id
DELETE /api/article/{id} Delete an article by id
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
32. Install Node.js and Express.js
Install Node.js
◦ http://nodejs.org/download/
Install Express.js & Express.js Generator
Create a Express.js Project
32
$ npm install express express-generator -g
$ express myProject
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
34. Mongoose (2/2)
Connecting to MongoDB
Defining a Model
34
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database');
var Schema = mongoose.Schema;
var ArticleSchema = new Schema({
title: String,
author: String,
body: String,
datetime: { type: Date, default: Date.now }
});
mongoose.model('Article', ArticleSchema);
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
35. Design RESTful API (1/5)
Display all articles
35
router.get('/article', function (req, res, next) {
Article.find(function (err, articles) {
if (err) return next(err);
res.json(articles);
});
});
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
36. Design RESTful API (2/5)
Display an article
36
router.get('/article/:id', function (req, res, next) {
Article.findOne({ _id: req.params.id }, function (err, article) {
if (err) return next(err);
res.json(article);
});
});
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
37. Design RESTful API (3/5)
Create an article
37
router.post('/article', function (req, res, next) {
var article = new Article(req.body);
article.save(function (err) {
if (err) return next(err);
res.json({ message: 'Article Added' });
});
});
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
38. Design RESTful API (4/5)
Update an article
38
router.put('/article/:id', function (req, res, next) {
Article.findOne({ _id: req.params.id }, function(err, article) {
if (err) return next(err);
for (prop in req.body) {
article[prop] = req.body[prop];
}
article.save(function(err) {
if (err) return next(err);
res.json({ message: 'Article updated' });
});
});
});
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
39. Design RESTful API (5/5)
Delete an article
39
router.delete('/article/:id', function (req, res, next) {
Article.remove({_id: req.params.id}, function(err, article) {
if (err) return next(err);
res.json({ message: 'Successfully deleted' });
});
});
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
40. Use Postman for Testing
Postman is a free plugin for the Chrome browser.
40
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
41. Integrate with API
Using AngularJS to build web app.
MEAN stack is pure JavaScript solutions.
Demo
◦ https://mean-app-demo.herokuapp.com/
41
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB