CSCC09F Programming on the Web. Mongo DB



Similar documents
NoSQL web apps. w/ MongoDB, Node.js, AngularJS. Dr. Gerd Jungbluth, NoSQL UG Cologne,

MongoDB Developer and Administrator Certification Course Agenda

Getting Started with MongoDB

Introduction to NoSQL and MongoDB. Kathleen Durant Lesson 20 CS 3200 Northeastern University

MongoDB: document-oriented database

Perl & NoSQL Focus on MongoDB. Jean-Marie Gouarné jmgdoc@cpan.org

Scaling up = getting a better machine. Scaling out = use another server and add it to your cluster.

The full setup includes the server itself, the server control panel, Firebird Database Server, and three sample applications with source code.

.NET User Group Bern

Big Data & Data Science Course Example using MapReduce. Presented by Juan C. Vega

Frictionless Persistence in.net with MongoDB. Mogens Heller Grabe Trifork

MongoDB. Or how I learned to stop worrying and love the database. Mathias Stearn. N*SQL Berlin October 22th, gen

NO SQL! NO INJECTION?

Cloud Powered Mobile Apps with Azure

MongoDB in the NoSQL and SQL world. Horst Rechner Berlin,

NoSQL in der Cloud Why? Andreas Hartmann

Hacettepe University Department Of Computer Engineering BBM 471 Database Management Systems Experiment

The MongoDB Tutorial Introduction for MySQL Users. Stephane Combaudon April 1st, 2014

L7_L10. MongoDB. Big Data and Analytics by Seema Acharya and Subhashini Chellappan Copyright 2015, WILEY INDIA PVT. LTD.

No SQL! no injection? A talk on the state of NoSQL security

Big Data. Facebook Wall Data using Graph API. Presented by: Prashant Patel Jaykrushna Patel

Understanding NoSQL Technologies on Windows Azure

MarkLogic Server. Node.js Application Developer s Guide. MarkLogic 8 February, Copyright 2016 MarkLogic Corporation. All rights reserved.

How To Write A Web Server In Javascript

NoSQL Database - mongodb

Document Oriented Database

NoSQL replacement for SQLite (for Beatstream) Antti-Jussi Kovalainen Seminar OHJ-1860: NoSQL databases

Visualizing a Neo4j Graph Database with KeyLines

Lecture 21: NoSQL III. Monday, April 20, 2015

MongoDB. An introduction and performance analysis. Seminar Thesis

Big Data Solutions. Portal Development with MongoDB and Liferay. Solutions

Building Your First MongoDB Application

Certified MongoDB Professional VS-1058

MONGODB - THE NOSQL DATABASE

Open Source Technologies on Microsoft Azure

these three NoSQL databases because I wanted to see a the two different sides of the CAP

Why NoSQL? Your database options in the new non- relational world IBM Cloudant 1

Attacking MongoDB. Firstov Mihail

HO5604 Deploying MongoDB. A Scalable, Distributed Database with SUSE Cloud. Alejandro Bonilla. Sales Engineer abonilla@suse.com

SURVEY ON MONGODB: AN OPEN- SOURCE DOCUMENT DATABASE

The evolution of database technology (II) Huibert Aalbers Senior Certified Executive IT Architect

Application of NoSQL Database in Web Crawling

Brad Dayley. NoSQL with MongoDB

MongoDB. The Definitive Guide to. The NoSQL Database for Cloud and Desktop Computing. Apress8. Eelco Plugge, Peter Membrey and Tim Hawkins

NOSQL INTRODUCTION WITH MONGODB AND RUBY GEOFF

Overview of Databases On MacOS. Karl Kuehn Automation Engineer RethinkDB

Can the Elephants Handle the NoSQL Onslaught?

NoSQL Databases. Nikos Parlavantzas

ADVANCED DATABASES PROJECT. Juan Manuel Benítez V Gledys Sulbaran

Databases for text storage

Server-Side JavaScript Injection Bryan Sullivan, Senior Security Researcher, Adobe Secure Software Engineering Team July 2011

An Approach to Implement Map Reduce with NoSQL Databases

SQL Injection Vulnerabilities in Desktop Applications

Introducing DocumentDB

Preparing Your Data For Cloud

Analytics March 2015 White paper. Why NoSQL? Your database options in the new non-relational world

Programming Against Hybrid Databases with Java Handling SQL and NoSQL. Brian Hughes IBM

Avaya Inventory Management System

NoSQL Database Systems and their Security Challenges

PHP and MongoDB Web Development Beginners Guide by Rubayeet Islam

Oracle Database 10g Express

Benchmarking Couchbase Server for Interactive Applications. By Alexey Diomin and Kirill Grigorchuk

Scaling with MongoDB. by Michael Schurter Scaling with MongoDB by Michael Schurter - OS Bridge,

Getting Started with SandStorm NoSQL Benchmark

Big data and urban mobility

Cloud Scale Distributed Data Storage. Jürmo Mehine

Structured Data Storage

MongoDB and Couchbase

Server-Side JavaScript auf der JVM. Peter Doschkinow Senior Java Architect

NoSQL - What we ve learned with mongodb. Paul Pedersen, Deputy CTO paul@10gen.com DAMA SF December 15, 2011

MarkLogic Server. Reference Application Architecture Guide. MarkLogic 8 February, Copyright 2015 MarkLogic Corporation. All rights reserved.

How To Compare The Economics Of A Database To A Microsoft Database

NoSQL, But Even Less Security Bryan Sullivan, Senior Security Researcher, Adobe Secure Software Engineering Team

OAuth 2.0 Developers Guide. Ping Identity, Inc th Street, Suite 100, Denver, CO

Visualizing an OrientDB Graph Database with KeyLines

Chapter 11 Map-Reduce, Hadoop, HDFS, Hbase, MongoDB, Apache HIVE, and Related

KEYSTONE JS FOR DRUPAL DEVELOPERS

A COMPARATIVE STUDY OF NOSQL DATA STORAGE MODELS FOR BIG DATA

How graph databases started the multi-model revolution

Spring Data, Jongo & Co. Java Persistenz-Frameworks für MongoDB

Write Modern Web Apps with the MEAN Stack

Lag Sucks! R.J. Lorimer Director of Platform Engineering Electrotank, Inc. Robert Greene Vice President of Technology Versant Corporation

Database Design Patterns. Winter Lecture 24

Comparison of the Frontier Distributed Database Caching System with NoSQL Databases

Applied Internet Technology (CSCI-UA.0480) - Sample Questions

Connecting to Manage Your MS SQL Database

Comparisons Between MongoDB and MS-SQL Databases on the TWC Website

Cloud Powered Mobile Apps with Microsoft Azure

Introduction to Server-Side Programming. Charles Liu

Zero Downtime Deployments with Database Migrations. Bob Feldbauer

JavaScript Programming

How to Use PIPS Access to/from SQL Database Utility Program. By PIPSUS Support Team Dr. Chouikha

Referential Integrity in Cloud NoSQL Databases

Performance Evaluation of NoSQL Systems Using YCSB in a resource Austere Environment

Transcription:

CSCC09F Programming on the Web Mongo DB A document-oriented Database, mongoose for Node.js, DB operations 52 MongoDB CSCC09 Programming on the Web 1 CSCC09 Programming on the Web 1

What s Different in MongoDB? You already know about traditional relational DB s (C43) 52 MongoDB CSCC09 Programming on the Web 2 CSCC09 Programming on the Web 2

What s Different in MongoDB? Query results returned in JavaScript-friendly format > db.user.findone({age:21}) { "_id" :ObjectId("5327f8ea17 "), "first" : "Jeff", "last" : "Lee", "age" : 21, "interests" : [ "photography", "gaming"] "favorites": { "color": "red", "sport": "tennis"} } 52 MongoDB CSCC09 Programming on the Web 3 CSCC09 Programming on the Web 3

Create CRUD(Mongo native API) db.collection.insert( <document> ) db.collection.save( <document> ) db.collection.update( <query>, <update>, { upsert: true } ) // insert query not matched Read db.collection.find( <query>, <projection> ) db.collection.findone( <query>, <projection> ) Update db.collection.update( <query>, <update>, <options> ) Delete db.collection.remove( <query>, <justone> ) 52 MongoDB CSCC09 Programming on the Web 4 CSCC09 Programming on the Web 4

CRUD example > db.user.insert({ first: "Jeff", last : "Lee", age: 21 }) > db.user.find () { "_id" : ObjectId("51 "), "first" : "Jeff", "last" : "Lee", "age" : 21 } > db.user.update( {"_id": ObjectId("51 ")}, { $set: { age: 22, salary: 77000} } ) 5 > db.user.remove({ "first": /^J/ }) 52 MongoDB CSCC09 Programming on the Web CSCC09 Programming on the Web 5

Mongo Features Document-Oriented storage Full Index Support Replication +High Availability Auto-Sharding Flexible Queryingincluding Geospatial Map/Reducefor processing large datasets Agile Scalable 52 MongoDB CSCC09 Programming on the Web 6 CSCC09 Programming on the Web 6

Is Mongo Mainstream? Mongo isn t just an open-source project used for tinkering As of Oct 2015, is ranked as the 4 th most-used DB overall and 1 st place among NoSQL (document) DB s! 52 MongoDB CSCC09 Programming on the Web 7 CSCC09 Programming on the Web 7

Mongo: a Document DB Mongo is a document-oriented datastore, as compared with a set of related tables in a relational DB Document-oriented store maps more easily to domain models in JavaScript, e.g. Movie, Review Mongo represents documents as JSON, making it very easy to interface with Web apps, especially when the app server-side is implemented in JavaScript (e.g. Node.js) for efficiency DB stores a binary form of JSON named BSON Unlike a traditional relational DB, Mongo does not rely on a rigid table structure with columns and types (although can define schemas with types, as in Mongoose for Asst2) 52 MongoDB CSCC09 Programming on the Web 8 CSCC09 Programming on the Web 8

Mongo: a Document DB A Mongo DB is schema-less although we will define schemas in Mongoose which get evaluated every time you restart your Node.js server This means that like JavaScript s collections, the models in a MongoDB collection can have different field sets! This is advantageous if you need to change the structure of your data, as in an agile environment changing structure/schema of relational-database tables is a delicate operation get it wrong and your code is broken in a Mongo environment, change schema, restart Node.js. Any new model instances will have the new structure, old models will have undefined values for new field (beware!) 52 MongoDB CSCC09 Programming on the Web 9 CSCC09 Programming on the Web 9

Mongo with Node.js: Mongoose Mongoose module provides object modeling for Node.js similar idea to Object-Relational-Mapping (ORM) for traditional relational databases goal is to reduce the friction or gap between the objects/models used in the app programming language and the data stored in the database Mongoose translates DB data to JavaScript objects and vice versa Advantage is that as a developer you can think of the database as storing the same models used in your clientside code (Backbone Models) 52 MongoDB CSCC09 Programming on the Web 11 CSCC09 Programming on the Web 10

Mongo with Node.js: Mongoose Mongoose module provides object modeling for Node.js var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); // create Dog model-constructor, using circled Schema // 'Dog' is the singular name of the model s collection var Dog = mongoose.model('dog',{name: String}); // instantiate a new Dog model using constructor var pup = new Dog({ name: 'Boof' }); pup.save(function (err) { }); if (err) { //... } else { console.log('woof!'); } 52 MongoDB CSCC09 Programming on the Web 12 CSCC09 Programming on the Web 11

Mongo with Node.js: Mongoose var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var Dog = mongoose.model('dog',{name: String}); var pup = new Dog({ name: 'Boof' }); pup.save(function (err) { }); if (err) { //... } else { console.log('woof!'); } In mongoose.model('dog',{ }), Dogis the singular name of the collection (Dogs). The function-call result is a Model-constructor function that can be used to create instances of the model, which in turn are documents persisted by Mongo. pup is one such instance See save() example below for Asst2 related model 52 MongoDB CSCC09 Programming on the Web 13 CSCC09 Programming on the Web 12

Mongoose Connect to DB When using an authenticated database need to specify extra details at connect time (notethe :port part can be dropped when using the standard port, as on mathlab): var uri = 'mongodb://username:password mongoose.connect(uri); @hostname:port/database_name; Should specify username, password, database_namein your options.jsmodule 52 MongoDB CSCC09 Programming on the Web 14 CSCC09 Programming on the Web 13

Mongoose Schemas and Models A mongoose schemais associated with the model for a collection same idea as a collection-model in Backbone // Schemas var MovieSchema = new mongoose.schema({ }); title: { type: String, required: true }, director: { type: String, required:true }, // ADD CODE for other Movie attributes To be able to modify Movie, we need: Singular name of collection Schema name var Movie=mongoose.model('Movie',MovieSchema); 52 MongoDB CSCC09 Programming on the Web 17 CSCC09 Programming on the Web 14

Mongoose Schemas and Indices A mongoose schemais associated with the model for a collection same idea as a collection model in Backbone // Schemas var MovieSchema = new mongoose.schema({ }); title: { type: String, required: true }, director: { type: String, required:true }, // ADD CODE for other Movie attributes // impose constraint such as unique field-pair MovieSchema.index({ // field list }, { // constraint list }); 52 MongoDB CSCC09 Programming on the Web 18 CSCC09 Programming on the Web 15

Queries To retrieve all Movie instances: Movie.find({}, function(error, movies){ }); if (!error) res.send(movies); You can omit the {}parameter, as a syntactic abbreviation In general, the first parameter of.find() can be a JSON object such as: { title: 'Wild' } which behaves like SQL clause: WHERE title="wild" 52 MongoDB CSCC09 Programming on the Web 19 CSCC09 Programming on the Web 16

More Queries A special case of find()is used when model s id is known: Movie.findById(req.params.id, }); function(error, data){ res.json(data); Another special case of find is used when you want just a single result (here matches field-value pair): Movie.findOne({field: value}, }); function(error, data){ res.json(data); 52 MongoDB CSCC09 Programming on the Web 20 CSCC09 Programming on the Web 17

More Queries Queries are quite flexible: by field value, e.g. movie title: Movie.find({title: "Wild"}) by ranges, e.g. price value in range 10-30 Movie.find({released:{$gt:2009,$lt:2014}}) by regular expression, comparable to SQL s LIKE Movie.find({starring: /Keanu/}) Result of a query can be one or more documents (models) or fields of those documents, e.g. could return just the director (and id) field from all movies matching query by specifying projection as 2 nd parameter to find(): Movie.find({starring:/Keanu/},{director:1}) 52 MongoDB CSCC09 Programming on the Web 21 CSCC09 Programming on the Web 18

Saving New Model // create new movie instance var movie = new Movie( attributes ); // save to database, with callback to // return result and handle errors movie.save(function(error, movie){ }); if(!error){ // return model to client res.status(200).send(movie); } else {... handle errors } 52 MongoDB CSCC09 Programming on the Web 24 CSCC09 Programming on the Web 19

Updating Existing Model Movie.findById(req.params.id, function(finderr, movie){ if(!finderr && movie){ // update movie attributes from req.body movie.save(function(saveerr, movieresp) { if (!saveerr) { // return model res.status(200).send(movieresp); } else {... handle error } }); } else {... handle error }; }); 52 MongoDB CSCC09 Programming on the Web 25 CSCC09 Programming on the Web 20

Mongo: performance features Any document field can be designated as an index, for faster index-based querying Mongo supports DB replication, so that if your primary datastorefails, a replica datastore takes over Mongo supports shardingfor load balancing, with set of documents in a DB distributed across multiple servers, based on user-selected shard-key, e.g. city field 52 MongoDB CSCC09 Programming on the Web 26 CSCC09 Programming on the Web 21