MongoDB - a quick look
Each document can have different fields of data!!!
every document in a collection will be assigned a unique value of _id.
it is like it's primary key
Pros of Document Database |
Cons of Document Database |
|
|
|
|
|
|
Applications that require complex, multi-row transactions (e.g., a double-entry bookkeeping system) |
"provides elegant MongoDB object modeling for Node.js"
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 documentvar 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 firstvar 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);