SlideShare una empresa de Scribd logo
1 de 43
An Open Source Document Database
王雋凱 ▪ 曾亭媗 ▪ 林子鈞/IDSL - Dept. of IM - NTUST
12017/1/30
Outline
Introduction to MongoDB
MongoDB Installation
MongoDB CRUD Operations
RESTful API Implementation
2
Introduction to MongoDB
MongoDB 簡介
3
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
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
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
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
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
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
BSON Types
◦ Double 浮點數
◦ String 字串
◦ Object 物件
◦ Array 陣列
◦ Binary data 二進位資料
◦ Undefined Deprecated
◦ Object id 物件編號
◦ Boolean 布林
◦ Date 日期
◦ Null 空字元
◦ Regular Expression 正規表示式
◦ JavaScript JavaScript
◦ Symbol 符號
◦ JavaScript (with scope) JavaScript (with scope)
◦ 32-bit integer 32 位元整數
◦ Timestamp 時間戳
◦ 64-bit integer 64 位元整數
◦ Min key 最大值
◦ Max key 最小值
10
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
DB-Engines Ranking
http://db-engines.com/en/ranking
11
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
MongoDB Installation
安裝 MongoDB
12
Installation
http://www.mongodb.org/downloads
13
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
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
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
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
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
Documentation
http://docs.mongodb.org/manual/
18
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
MongoDB CRUD Operations
MongoDB 資料的新增、讀取、修改、刪除之操作
19
Document & Collection
Document Collection
20
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
Insert Documents (1/2)
Insert a document
21
db.inventory.insert(
{
item: "ABC1",
details: {
model: "14Q3",
manufacturer: "XYZ Company"
},
stock: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ],
category: "clothing"
}
)
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
Insert Documents (2/2)
Insert an Array of Documents
◦ Create an array of documents
◦ Insert the documents
22
var mydocuments =
[
{
item: "ABC2",
details: { model: "14Q3", manufacturer: "M1 Corporation" },
stock: [ { size: "M", qty: 50 } ],
category: "clothing"
},
{
item: "MNO2",
details: { model: "14Q3", manufacturer: "ABC Company" },
stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 }, { size: "L", qty: 1 } ],
category: "clothing"
},
];
db.inventory.insert( mydocuments );
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
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
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
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
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
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
Modify Documents (2/2)
Update multiple documents
28
db.inventory.update(
{ category: "clothing" },
{
$set: { category: "apparel" },
$currentDate: { lastModified: true }
},
{ multi: true }
)
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
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
RESTful API Implementation
RESTful API 實作 – 使用 Node.js、Express.js 和 MongoDB
30
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
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
Mongoose (1/2)
關聯式資料庫有 ORM (Object-relational Mapper)
文件式資料庫有 ODM (Object-document Mapper)
Mongoose
◦ Officially supported ODM (Object-document Mapper) for Node.js
◦ Advanced schema-based features
◦ Object life-cycle management
◦ Documentation:http://mongoosejs.com/
33
$ npm install mongoose --save
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
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
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
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
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
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
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
Use Postman for Testing
Postman is a free plugin for the Chrome browser.
40
MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
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
Sample Code
https://github.com/chunkai1312/mean-app-demo
42
Thank You!
43

Más contenido relacionado

La actualidad más candente

Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in AngularYakov Fain
 
Using ReactJS in AngularJS
Using ReactJS in AngularJSUsing ReactJS in AngularJS
Using ReactJS in AngularJSBoris Dinkevich
 
Open Service Broker APIとKubernetes Service Catalog #k8sjp
Open Service Broker APIとKubernetes Service Catalog #k8sjpOpen Service Broker APIとKubernetes Service Catalog #k8sjp
Open Service Broker APIとKubernetes Service Catalog #k8sjpToshiaki Maki
 
Designing applications with Redux
Designing applications with ReduxDesigning applications with Redux
Designing applications with ReduxFernando Daciuk
 
Realm database
Realm databaseRealm database
Realm databaseVoneat Pen
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersNaresha K
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkRed Hat Developers
 
Powershell For Developers
Powershell For DevelopersPowershell For Developers
Powershell For DevelopersIdo Flatow
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov Fain
 
Redux. From twitter hype to production
Redux. From twitter hype to productionRedux. From twitter hype to production
Redux. From twitter hype to productionFDConf
 
Android HttpClient - new slide!
Android HttpClient - new slide!Android HttpClient - new slide!
Android HttpClient - new slide!Chalermchon Samana
 
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1Toshiaki Maki
 
AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)Nitya Narasimhan
 
Dropwizard Internals
Dropwizard InternalsDropwizard Internals
Dropwizard Internalscarlo-rtr
 

La actualidad más candente (20)

React render props
React render propsReact render props
React render props
 
Grails Plugins
Grails PluginsGrails Plugins
Grails Plugins
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in Angular
 
Using ReactJS in AngularJS
Using ReactJS in AngularJSUsing ReactJS in AngularJS
Using ReactJS in AngularJS
 
Open Service Broker APIとKubernetes Service Catalog #k8sjp
Open Service Broker APIとKubernetes Service Catalog #k8sjpOpen Service Broker APIとKubernetes Service Catalog #k8sjp
Open Service Broker APIとKubernetes Service Catalog #k8sjp
 
Designing applications with Redux
Designing applications with ReduxDesigning applications with Redux
Designing applications with Redux
 
Realm database
Realm databaseRealm database
Realm database
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 
Powershell For Developers
Powershell For DevelopersPowershell For Developers
Powershell For Developers
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
Redux. From twitter hype to production
Redux. From twitter hype to productionRedux. From twitter hype to production
Redux. From twitter hype to production
 
React js
React jsReact js
React js
 
Intro to ReactJS
Intro to ReactJSIntro to ReactJS
Intro to ReactJS
 
Android HttpClient - new slide!
Android HttpClient - new slide!Android HttpClient - new slide!
Android HttpClient - new slide!
 
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
 
AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)
 
Using redux
Using reduxUsing redux
Using redux
 
Dropwizard Internals
Dropwizard InternalsDropwizard Internals
Dropwizard Internals
 

Destacado

Android NFC Application Development Environment Setup
Android NFC Application Development Environment SetupAndroid NFC Application Development Environment Setup
Android NFC Application Development Environment SetupChun-Kai Wang
 
Android Application Development of NFC Reader-Writer Mode
Android Application Development of NFC Reader-Writer ModeAndroid Application Development of NFC Reader-Writer Mode
Android Application Development of NFC Reader-Writer ModeChun-Kai Wang
 
Introduction to CodeIgniter
Introduction to CodeIgniterIntroduction to CodeIgniter
Introduction to CodeIgniterChun-Kai Wang
 
Mobility Aware Distributed Service Composition Framework in SOA based MANET A...
Mobility Aware Distributed Service Composition Framework in SOA based MANET A...Mobility Aware Distributed Service Composition Framework in SOA based MANET A...
Mobility Aware Distributed Service Composition Framework in SOA based MANET A...Chun-Kai Wang
 
友增吾簡-互動式名片系統
友增吾簡-互動式名片系統友增吾簡-互動式名片系統
友增吾簡-互動式名片系統Chun-Kai Wang
 
NFC-based User Authentication Mechanisms for Personalized IPTV Services
NFC-based User Authentication Mechanisms for Personalized IPTV ServicesNFC-based User Authentication Mechanisms for Personalized IPTV Services
NFC-based User Authentication Mechanisms for Personalized IPTV ServicesChun-Kai Wang
 
Nfc reader writer_mode
Nfc reader writer_modeNfc reader writer_mode
Nfc reader writer_modeChun-Kai Wang
 
Android Application Development of NFC Peer-to-Peer Mode
Android Application Development of NFC Peer-to-Peer ModeAndroid Application Development of NFC Peer-to-Peer Mode
Android Application Development of NFC Peer-to-Peer ModeChun-Kai Wang
 

Destacado (8)

Android NFC Application Development Environment Setup
Android NFC Application Development Environment SetupAndroid NFC Application Development Environment Setup
Android NFC Application Development Environment Setup
 
Android Application Development of NFC Reader-Writer Mode
Android Application Development of NFC Reader-Writer ModeAndroid Application Development of NFC Reader-Writer Mode
Android Application Development of NFC Reader-Writer Mode
 
Introduction to CodeIgniter
Introduction to CodeIgniterIntroduction to CodeIgniter
Introduction to CodeIgniter
 
Mobility Aware Distributed Service Composition Framework in SOA based MANET A...
Mobility Aware Distributed Service Composition Framework in SOA based MANET A...Mobility Aware Distributed Service Composition Framework in SOA based MANET A...
Mobility Aware Distributed Service Composition Framework in SOA based MANET A...
 
友增吾簡-互動式名片系統
友增吾簡-互動式名片系統友增吾簡-互動式名片系統
友增吾簡-互動式名片系統
 
NFC-based User Authentication Mechanisms for Personalized IPTV Services
NFC-based User Authentication Mechanisms for Personalized IPTV ServicesNFC-based User Authentication Mechanisms for Personalized IPTV Services
NFC-based User Authentication Mechanisms for Personalized IPTV Services
 
Nfc reader writer_mode
Nfc reader writer_modeNfc reader writer_mode
Nfc reader writer_mode
 
Android Application Development of NFC Peer-to-Peer Mode
Android Application Development of NFC Peer-to-Peer ModeAndroid Application Development of NFC Peer-to-Peer Mode
Android Application Development of NFC Peer-to-Peer Mode
 

Similar a Introduction to MongoDB

Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code維佋 唐
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBMongoDB
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBMongoDB
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsMongoDB
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsMongoDB
 
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBTobias Trelle
 
Back to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDBBack to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDBMongoDB
 
Back to Basics Webinar 2 - Your First MongoDB Application
Back to  Basics Webinar 2 - Your First MongoDB ApplicationBack to  Basics Webinar 2 - Your First MongoDB Application
Back to Basics Webinar 2 - Your First MongoDB ApplicationJoe Drumgoole
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationMongoDB
 
AWS Webcast - Build Agile Applications in AWS Cloud for Government
AWS Webcast - Build Agile Applications in AWS Cloud for GovernmentAWS Webcast - Build Agile Applications in AWS Cloud for Government
AWS Webcast - Build Agile Applications in AWS Cloud for GovernmentAmazon Web Services
 
Test Automation for NoSQL Databases
Test Automation for NoSQL DatabasesTest Automation for NoSQL Databases
Test Automation for NoSQL DatabasesTobias Trelle
 
Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch Application to the Next Level...
Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch Application to the Next Level...Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch Application to the Next Level...
Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch Application to the Next Level...MongoDB
 
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...MongoDB
 
Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Kuo-Chun Su
 
MongoDB.local Paris Keynote
MongoDB.local Paris KeynoteMongoDB.local Paris Keynote
MongoDB.local Paris KeynoteMongoDB
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBMongoDB
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Tobias Trelle
 

Similar a Introduction to MongoDB (20)

Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
MongoDB and Node.js
MongoDB and Node.jsMongoDB and Node.js
MongoDB and Node.js
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
Back to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDBBack to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDB
 
Back to Basics Webinar 2 - Your First MongoDB Application
Back to  Basics Webinar 2 - Your First MongoDB ApplicationBack to  Basics Webinar 2 - Your First MongoDB Application
Back to Basics Webinar 2 - Your First MongoDB Application
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB Application
 
AWS Webcast - Build Agile Applications in AWS Cloud for Government
AWS Webcast - Build Agile Applications in AWS Cloud for GovernmentAWS Webcast - Build Agile Applications in AWS Cloud for Government
AWS Webcast - Build Agile Applications in AWS Cloud for Government
 
Test Automation for NoSQL Databases
Test Automation for NoSQL DatabasesTest Automation for NoSQL Databases
Test Automation for NoSQL Databases
 
Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch Application to the Next Level...
Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch Application to the Next Level...Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch Application to the Next Level...
Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch Application to the Next Level...
 
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
 
Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Spring Data MongoDB 介紹
Spring Data MongoDB 介紹
 
MongoDB.local Paris Keynote
MongoDB.local Paris KeynoteMongoDB.local Paris Keynote
MongoDB.local Paris Keynote
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Spring Data, Jongo & Co.
Spring Data, Jongo & Co.
 

Último

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Último (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

Introduction to MongoDB

  • 1. An Open Source Document Database 王雋凱 ▪ 曾亭媗 ▪ 林子鈞/IDSL - Dept. of IM - NTUST 12017/1/30
  • 2. Outline Introduction to MongoDB MongoDB Installation MongoDB CRUD Operations RESTful API Implementation 2
  • 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
  • 10. BSON Types ◦ Double 浮點數 ◦ String 字串 ◦ Object 物件 ◦ Array 陣列 ◦ Binary data 二進位資料 ◦ Undefined Deprecated ◦ Object id 物件編號 ◦ Boolean 布林 ◦ Date 日期 ◦ Null 空字元 ◦ Regular Expression 正規表示式 ◦ JavaScript JavaScript ◦ Symbol 符號 ◦ JavaScript (with scope) JavaScript (with scope) ◦ 32-bit integer 32 位元整數 ◦ Timestamp 時間戳 ◦ 64-bit integer 64 位元整數 ◦ Min key 最大值 ◦ Max key 最小值 10 MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
  • 11. DB-Engines Ranking http://db-engines.com/en/ranking 11 MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
  • 13. Installation http://www.mongodb.org/downloads 13 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
  • 18. Documentation http://docs.mongodb.org/manual/ 18 MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
  • 19. MongoDB CRUD Operations MongoDB 資料的新增、讀取、修改、刪除之操作 19
  • 20. Document & Collection Document Collection 20 MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
  • 21. Insert Documents (1/2) Insert a document 21 db.inventory.insert( { item: "ABC1", details: { model: "14Q3", manufacturer: "XYZ Company" }, stock: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ], category: "clothing" } ) MongoDB Installation MongoDB CRUD Operations RESTful API ImplementationIntroduction to MongoDB
  • 22. Insert Documents (2/2) Insert an Array of Documents ◦ Create an array of documents ◦ Insert the documents 22 var mydocuments = [ { item: "ABC2", details: { model: "14Q3", manufacturer: "M1 Corporation" }, stock: [ { size: "M", qty: 50 } ], category: "clothing" }, { item: "MNO2", details: { model: "14Q3", manufacturer: "ABC Company" }, stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 }, { size: "L", qty: 1 } ], category: "clothing" }, ]; db.inventory.insert( mydocuments ); 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
  • 28. Modify Documents (2/2) Update multiple documents 28 db.inventory.update( { category: "clothing" }, { $set: { category: "apparel" }, $currentDate: { lastModified: true } }, { multi: 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
  • 30. RESTful API Implementation RESTful API 實作 – 使用 Node.js、Express.js 和 MongoDB 30
  • 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
  • 33. Mongoose (1/2) 關聯式資料庫有 ORM (Object-relational Mapper) 文件式資料庫有 ODM (Object-document Mapper) Mongoose ◦ Officially supported ODM (Object-document Mapper) for Node.js ◦ Advanced schema-based features ◦ Object life-cycle management ◦ Documentation:http://mongoosejs.com/ 33 $ npm install mongoose --save 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

Notas del editor

  1. 大家好,我今天要介紹MongoDB
  2. 什麼是MongoDB? 它不使用關聯式模型,是文件導向的資料庫,也就是說它沒有schema ,不同文件的資料屬性值可以都不同,但這些文件仍然能夠存在相同的集合中。 MongoDB實作了複製,使用複製組來提供高可達性。複製組通常被用在資料多餘量(data redundancy)、 自動從錯誤中回復(automated failover)、讀取擴充、不用關閉伺服器即可維護以及災難回復的情況下。 關於查詢方面,MongoDB實作map-reduce,使它查詢較簡單,因為物件內嵌(ㄑㄧㄢ)在單一物件中, 能夠基於內嵌(ㄑㄧㄢ)的子物件作查詢。   關於擴充性,MongoDB可以新增節點或變更資料儲存,而不用將資料庫移植到一個更大的機器上。
  3. 為何使用MongoDB? SQL 是1970年代發明的產物 歷史久遠 不一定適合用在現在big data的環境中, MongoDB是 文件導向資料庫 基本上儲存格式是json 物件, 現在許多物件程式語言大量操作json資料, 那為何不把json資料直接儲存在db裡?基本上這樣的思維就是MongoDB的設計哲學。
  4. 什麼狀況適合使用MongoDB? 像是 事件歷史紀錄 內容管理系統 即時資料分析 電子商務應用程式 等
  5. 不適合使用MongoDB 像是 包括許多不同動作的複雜交易 或在不同的聚合結構上查詢 等
  6. MongoDB特色方面 簡單的查詢語句,沒有 join 操作 資料使用 Binary JSON 儲存 提供 自動分割實現資料的擴展性 可以對 document 的某個數組屬性建立索引 可以用於進行複雜的統計和平行計算 等等
  7. 這是 關聯式db和MongoDB的專有名詞比較: 像關聯式db的table在MongoDB叫collection 關聯式db的row在MongoDB是document 關聯式db的column(卡 ㄌㄥˋ) 在MongoDB是 field(fi yo d) MongoDB的collection都有一個特定的id
  8. 這是MongoDB儲存資料的型態
  9. 這是目前使用db的排名,前四名為關聯式db,MongoDB是目前最多人使用的NoSQL DB