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