MongoDB - a quick look

 

 

Leveraging your knowledge of traditional databases

Each document can have different fields of data!!!

A note about the special field _id

 

every document in a collection will be assigned a unique value of _id.
it is like it's primary key

 

 

 

Some andedotal pros/cons of a Document Database (like MongoDB) over a Relational Database (like Oracle, MySQL)

 

Pros of Document Database

Cons of Document Database
*** or why use relational instead

  1. you can easily add new 'columns' and 'tables'
  2. speed (****not really true over professional RDMS***)
  3. sharding
  4. document matches more closely to an object than a set of relational tables so mapping becomes easier
  5. It broadens the mind
  1. (the lack of / different vision on) durability (read http://www.mikealrogers.com/2010/07/mongodb-performance-durability)
  2. No transactions
  3. No constraints
  4. Aggregation with MapReduce is slow and you need to write code for something like group-by
  5. Reporting is harder, the developer defines the relations but business analysts can't build their own queries, they can't for example do a 'minus' ('except' in sql server lingo)
  • No more SQL statements
  • Your database resembles your classes not the other way around
  • Your "schema" is more flexible
  • Scales well
  • Very easy to get started with
  • < opinion>It's cool< / opinion>
 
  • Flexible to change data format/schema during development
  • Simpler (in many ways) product and management tools 

 

  • Doing extensive reporting on the stored data can be harder when using MongoDB or any document database and some use cases have been combining RDBMS and document-db for that purpose.
  Applications that require complex, multi-row transactions (e.g., a double-entry bookkeeping system)

 

 

 

Mongoose in MongoDB --adding more structure --to make program reliability better?

"provides elegant MongoDB object modeling for Node.js"

 

 

MongoDB and NodeJS

Connecting

var mongodb = require('mongodb');
// Standard URI format:  mongodb://[dbuser:dbpassword@]host:port/dbname
// GO TO mLab.com account to see what YOUR database URL is 
//CHANGE the url so it is correct for your account
var uri ='mongodb://YOUR_LOGIN:YOURPASSWROD@WHATEVER.mlab.com:xxxxx/dnName';
//using mongodb module 
mongodb.MongoClient.connect(uri, function(err,  client){
     if(err) throw err;
     var theDatabase = client.db('dbName');
 
     var db = theDatabase.collection('collenctionName');

     // NOW DO WHAT YOU WANT -- CRUD

		db.close();  //close database connection when you are done

}

CRUD - data manipulation (Create Read Update Delete) -- read mongoDB site for more including bulk writes

 

********* 2 great sources:

 

Insert --like create

insert - in collection dogs where have document with field age=1
var r = yield db.collection('dogs').insertOne({name:"fido", age:1});

assert.equal(1, r.insertedCount);

 

//single insert where have 2rd parameter to insertOne() that has call back function that check for errors

  db.collection('dogs').insertOne({ name: "fido", age: 1 }, function(err, res) {
    if (err) throw err;
    console.log("1 document inserted");
    db.close();
  });

 

//multiple inserts - in collection dogs where have 2 new documents inserted

var r = yield db.collection('dogs').insertMany([{name:"spot" , age:2}, {name:"rex", age:3}]);

assert.equal(2, r.insertedCount);

 

 

//Another multiple insert example-- where check if any errors and inserting on the collection called customers
   var myobj = [
    { name: 'John', address: 'Highway 71'},
     { name: 'Peter', address: 'Lowstreet 4'},
    { name: 'Amy' address: 'Apple st 652'},
    { name: 'Hannah', address:  'Mountain 21'},
    { name: 'Michael', address: 'Valley 345'},
    { name: 'Sandy', address: 'Ocean blvd 2'},
     { name: 'Betty', address: 'Green Grass 1'},
    { name:  'Richard', address: 'Sky st 331'},
    { name: 'Susan' address: 'One way 98'},
    { name: 'Vicky', address:  'Yellow Garden 2'},
    { name: 'Ben', address: 'Park Lane 38'},
    { name: 'William', address: 'Central st 954'},
     { name: 'Chuck', address: 'Main Road 989'},
    { name:  'Viola', address: 'Sideway 1633'}
  ];
  db.collection("customers").insertMany(myobj,  function(err, res) {
    if (err) throw err;
     console.log("Number of documents inserted: " + res.insertedCount);
     db.close();
  });
});

 

FIND -- like read

//Example that finds ALL the documents in the dogs collection & gets results in an array you can cycle through

db.collection("dogs").find({}).toArray(function(err, result) {
     if (err) throw err;
    console.log(result); //simply dump out the results but, result is an array result[i] is ith document retrieved.

       for(i=0; i< result.length; i++)
              console.log(result[i]);
     db.close();
  });

//Example that finds all the dogs with age 3

  var query = {age: 3}; //query is comma separated conditional --JSON format
  db.collection("dogs").find(query).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });

//FIND example--where cycle through the returned documents as a cursor type datastructure rather than array
// Get the collection
var col = db.collection('dogs');

// Save find results in local variable cursor

var cursor = col.find({age:1}).limit(2); //find the first 2 dog documents ("entries") that have the field of age=1

// Iterate over retrieved documents

while(yield cursor.hasNext()) {

     var doc = yield cursor.next();

     console.dir(doc);

}

// Example that finds all the dogs in a collection and then applies sort on them based on alphanumeric ordering on the name field

var mysort = { name: 1 }; //specifies alphanumeric sort on field name
  db.collection("dogs").find().sort(mysort).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });

VISIT the API page for more examples including REGULAR expresssions for finding certain string patterns

https://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html

 

Update

//UPDATING

//first setup the collection

var col = db.collection('dogs');
// Insert a single document
var r = yield col.insertMany([{name:"fido", age:1}, {name:"spot", age:2}, {name:"rex", age:3}]);
assert.equal(
3, r.insertedCount);

// Update a single document

var r = yield col.updateOne({name:"fido"}, {$set: {age: 2}}); //change fido dog's age to 2
assert.equal(
1, r.matchedCount);
assert.equal(
1, r.modifiedCount);

// Update multiple documents
var r = yield col.updateMany({age:2}, {$set: {age: 3}}); //change all dogs with age of 2 to age 3
assert.equal(
2, r.matchedCount);
assert.equal(
2, r.modifiedCount);

 

Delete

//first setup the collection

var col = db.collection('dogs');

// Insert a some dogs first

var r = yield col.insertMany([{name:"fido", age:1}, {name:"spot", age:2}, {name:"rex", age:2}]);
assert.equal(
3, r.insertedCount);

//delete the first docuemnt found with age= 1
var r = yield col.deleteOne({age:1});
assert.equal(
1, r.deletedCount);

//delete multiple documents found with age=2

var r = yield col.deleteMany({age:2});
assert.equal(
2, r.deletedCount);

 

 

 

 

© Lynne Grewe