Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Last active August 29, 2015 14:03
Show Gist options
  • Save saintc0d3r/8e5f5ca372c016e3e834 to your computer and use it in GitHub Desktop.
Save saintc0d3r/8e5f5ca372c016e3e834 to your computer and use it in GitHub Desktop.
[MongoDb][Node.js] Create-Retrieve-Update-Delete (CRUD) in mongodb
/**
* A Simple demonstration of documents inserts against mongodb replica set
*/
var MongoClient = require('mongodb').MongoClient,
assert=require('assert');
var connection_string = "mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019/pcshop";
console.log("[INFO] - Connecting to "+connection_string+" ...");
MongoClient.connect(connection_string, function(err, db){
if (err) throw err;
console.log('[INFO] - Connection is established.');
// Insert items into the products collection
var products = db.collection('products');
var items = [
{'manufacturer': 'Intel', 'category':'CPUs-Processors-Desktop', 'description':'Intel Core i7-4960X Ivy Bridge-E 6-Core 3.6GHz (Turbo 4GHz) LGA 2011 130W Desktop Processor BX80633i74960X', 'price': 1049.99, 'quantity':12, 'last_updated': new Date(2014,06,26) },
{'manufacturer': 'ASUS', 'category':'Intel Motherboards', 'description':'ASUS Sabertooth X79 LGA 2011 Intel X79 SATA 6Gb/s USB 3.0 ATX Intel Motherboard', 'price': 314.99, 'quantity':24, 'last_updated': new Date(2014,04,20) },
{'manufacturer': 'Corsair', 'category':'Desktop Memory', 'description':'CORSAIR Dominator Platinum 16GB (2 x 8GB) 240-Pin DDR3 SDRAM DDR3 2400 Desktop Memory Model CMD16GX3M2A2400C10', 'price': 274.99, 'quantity':120, 'last_updated': new Date(2014,06,29) },
{'manufacturer': 'Zotac', 'category':'Desktop Graphics Card', 'description':'ZOTAC ZT-70301-10P GeForce GTX 770 2GB 256-Bit GDDR5 PCI Express 3.0 Video Card', 'price': 371.90, 'quantity':60, 'last_updated': new Date(2014,06,27) },
{'manufacturer': 'Gigabyte', 'category':'Desktop Graphics Card', 'description':'GIGABYTE GV-N770OC-4GD GeForce GTX 770 4GB 256-Bit GDDR5 PCI Express 3.0 HDCP Ready WindForce 3X 450W Video Card', 'price': 369.99, 'quantity':30, 'last_updated': new Date(2014,06,29) }
];
// Enter asynchronous for each loop
items.forEach(function(value, index, traversed_array){
// Insert current document into mongodb
products.insert(value, function(err, insertedDoc){
if (err) throw err;
assert.ok(insertedDoc.length > 0);
console.log("[INFO] - Successfully inserted "+JSON.stringify(insertedDoc[0])+" document." );
if (index == items.length-1){
console.log("[INFO] - Closing connection ...");
db.close();
}
});
});
});
/**
* A sample of findOne (retrieve a single document from a collection).
* Pre-requisite: the database & collection created in 01_insert.js exists.
*/
var MongoClient = require('mongodb').MongoClient,
assert=require('assert');
var connection_string = "mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019/pcshop";
console.log("[INFO] - Connecting to "+connection_string+" ...");
MongoClient.connect(connection_string, function(err, db){
if (err) throw err;
console.log('[INFO] - Connection is established.');
var products = db.collection('products');
// Declare the helper method for findOne Operation
function findOne(query, callback){
products.findOne(query, function(err, document){
console.log('[INFO] - Dispatched findOne ...');
if (err) throw err;
assert.ok(document != null);
console.log("[INFO] - findOne successfully returns "+JSON.stringify(document)+" document.");
if (callback != null){
callback();
}
});
}
// Find a document that has lowest Id compared to the others
findOne({}, function(){
// Query a document with specific criteria after prior query is finished
var zotac_gpu_query = {'manufacturer': 'Zotac', 'category': {$regex: 'Graphics Card'}};
findOne(zotac_gpu_query, function(){
console.log("[INFO] - Closing connection ...");
db.close();
});
});
});
/**
* A sample of find query with result projection.
* Pre-requisite: the database & collection created in 01_insert.js exists.
*/
var MongoClient = require('mongodb').MongoClient,
assert=require('assert');
var connection_string = "mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019/pcshop";
console.log("[INFO] - Connecting to "+connection_string+" ...");
MongoClient.connect(connection_string, function(err, db){
if (err) throw err;
console.log('[INFO] - Connection is established.');
var products = db.collection('products');
// Declare the helper method for find Operation
function find(query, projection, callback){
// The result of find method is a cursor. We call toArray method here to get the actual queried documents
products.find(query, projection).toArray(function(err, documents){
console.log('[INFO] - Dispatched find ...');
if (err) throw err;
assert.ok((documents != null) && (documents.length > 0));
console.log("[INFO] - find successfully returns "+documents.length+" documents:");
console.dir(documents);
if (callback != null){
callback();
}
});
}
// Pull all documents from the products collection
console.log("[INFO] - Pull all documents in the products collection");
find({},{}, function(){
// Query all documents that are categorised as 'Desktop Graphics Card'
console.log("[INFO] - Query all documents that are categorised as 'Desktop Graphics Card'.");
var desktop_graphics_card_query = {'category': 'Desktop Graphics Card'};
// also, project the query results so that each of the result would exclude _id & last_updated fields
var projection = {_id: 0, 'last_updated': 0};
find(desktop_graphics_card_query, projection, function(){
console.log("[INFO] - Closing connection ...");
db.close();
});
});
});
/**
* A sample of find with $gt & $lt operators.
* Pre-requisite: the database & collection created in 01_insert.js exists.
*/
var MongoClient = require('mongodb').MongoClient,
assert=require('assert');
var connection_string = "mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019/pcshop";
console.log("[INFO] - Connecting to "+connection_string+" ...");
MongoClient.connect(connection_string, function(err, db){
if (err) throw err;
console.log('[INFO] - Connection is established.');
var products = db.collection('products');
// Declare the helper method for find Operation
function find(query, callback){
// The result of find method is a cursor. We call toArray method here to get the actual queried documents
var hide_id_projection = {'_id':0};
products.find(query, hide_id_projection).toArray(function(err, documents){
console.log('[INFO] - Dispatched find ...');
if (err) throw err;
assert.ok((documents != null) && (documents.length > 0));
console.log("[INFO] - find successfully returns "+documents.length+" documents:");
console.dir(documents);
if (callback != null){
callback();
}
});
}
// Pull products where their price is greater than $300.0
console.log("[INFO] - Pull products where their price is greater than $300.0");
var query = {'price': {$gt: 300.0}};
find( query, function(){
// Query all documents where their price falls between $300-$400 range.
console.log("[INFO] - Query all documents where their price falls between $300-$400 range.");
query.price = {$gt: 300.0, $lt: 400.0};
find(query, function(){
console.log("[INFO] - Closing connection ...");
db.close();
});
});
});
/**
* A sample of find with $regex operator.
* Pre-requisite: the database & collection created in 01_insert.js exists.
*/
var MongoClient = require('mongodb').MongoClient,
assert=require('assert');
var connection_string = "mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019/pcshop";
console.log("[INFO] - Connecting to "+connection_string+" ...");
MongoClient.connect(connection_string, function(err, db){
if (err) throw err;
console.log('[INFO] - Connection is established.');
var products = db.collection('products');
// Declare the helper method for find Operation
function find(query, callback){
// The result of find method is a cursor. We call toArray method here to get the actual queried documents
var hide_id_projection = {'_id':0};
products.find(query, hide_id_projection).toArray(function(err, documents){
console.log('[INFO] - Dispatched find ...');
if (err) throw err;
assert.ok((documents != null) && (documents.length > 0));
console.log("[INFO] - find successfully returns "+documents.length+" documents:");
console.dir(documents);
if (callback != null){
callback();
}
});
}
// Pull products where their description contains 'i7'
console.log("[INFO] - Pull products where their description contains 'i7'");
var query = {'description': {$regex: 'i7'}};
find( query, function(){
console.log("[INFO] - Closing connection ...");
db.close();
});
});
/**
* A sample of find with $or operator.
* Pre-requisite: the database & collection created in 01_insert.js exists.
*/
var MongoClient = require('mongodb').MongoClient,
assert=require('assert');
var connection_string = "mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019/pcshop";
console.log("[INFO] - Connecting to "+connection_string+" ...");
MongoClient.connect(connection_string, function(err, db){
if (err) throw err;
console.log('[INFO] - Connection is established.');
var products = db.collection('products');
// Declare the helper method for find Operation
function find(query, callback){
// The result of find method is a cursor. We call toArray method here to get the actual queried documents
var hide_id_projection = {'_id':0};
products.find(query, hide_id_projection).toArray(function(err, documents){
console.log('[INFO] - Dispatched find ...');
if (err) throw err;
assert.ok((documents != null) && (documents.length > 0));
console.log("[INFO] - find successfully returns "+documents.length+" documents:");
console.dir(documents);
if (callback != null){
callback();
}
});
}
// Pull products where their manufacturers are ASUS or Zotac
console.log("[INFO] - Pull products where their manufacturers are ASUS or Zotac");
var query = {$or: [{'description': 'ASUS'},{'description': 'Zotac'}]};
find( query, function(){
console.log("[INFO] - Closing connection ...");
db.close();
});
});
/**
* A sample of find with $and operator.
* Pre-requisite: the database & collection created in 01_insert.js exists.
*/
var MongoClient = require('mongodb').MongoClient,
assert=require('assert');
var connection_string = "mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019/pcshop";
console.log("[INFO] - Connecting to "+connection_string+" ...");
MongoClient.connect(connection_string, function(err, db){
if (err) throw err;
console.log('[INFO] - Connection is established.');
var products = db.collection('products');
// Declare the helper method for find Operation
function find(query, callback){
// The result of find method is a cursor. We call toArray method here to get the actual queried documents
var hide_id_projection = {'_id':0};
products.find(query, hide_id_projection).toArray(function(err, documents){
console.log('[INFO] - Dispatched find ...');
if (err) throw err;
assert.ok((documents != null) && (documents.length > 0));
console.log("[INFO] - find successfully returns "+documents.length+" documents:");
console.dir(documents);
if (callback != null){
callback();
}
});
}
// Pull products where their category is Desktop Graphics Card AND their quantity is less than to 50
console.log("[INFO] - Pull products where their category is Desktop Graphics Card AND their quantity is less than equal to 50");
var query = {$and: [{'category': 'Desktop Graphics Card'},{'quantity': {$lte: 50}}]};
find( query, function(){
console.log("[INFO] - Closing connection ...");
db.close();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment