Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
saintc0d3r / 01_create_replica_set.sh
Last active August 29, 2015 14:03
[MongoDB] Creating a replica set ( a group of 3 or more mongod servers that behaves like RAID-1 disks) in a local machine
# NOTES: Adjust replSet, dbpath, port parameters as you see them fit on your system environments.
# Creates data directories for 3 mongod servers
mkdir -p /data/rs1 /data/rs2 /data/rs3
# Creates 3 mongod servers in local machine
mongod --replSet rs1 --logpath "node-1.log" --dbpath /data/rs1 --port 27018 --fork
mongod --replSet rs1 --logpath "node-2.log" --dbpath /data/rs2 --port 27019 --fork
mongod --replSet rs1 --logpath "node-3.log" --dbpath /data/rs3 --port 27020 --fork
@saintc0d3r
saintc0d3r / 01_aggregate_sum.js
Last active April 22, 2024 07:50
[MongoDb][Javascript-Mongo] Aggregate Queries in MongoDb ( $sum, $avg, $addToSet, $push, $max, $min, double grouping, $match, $project, $sort, $limit, $skip). To run these samples: mongo <sample js file>
// Let's say we have a store database
db = connect("localhost:27017/store");
var collectionNames = db.getCollectionNames();
for(var i=0; i < collectionNames.length; i++){
if (collectionNames[i] == "products"){
print("[INFO] - Products collection is exists. Dropping it now.");
db.products.drop();
break;
}
@saintc0d3r
saintc0d3r / 10_aggregate_project.js
Last active August 29, 2015 14:03
[MongoDb][MongoShell] Aggregate Queries in MongoDb ( $sum, $avg, $addToSet, $push, $max, $min, double grouping, $match, $project, $sort, $limit, $skip)
// We use the latest version of store database as shown in 9_aggregate_double_grouping.js
// Let's say , we want to reshape products list as follow:
// _id -------------> <excluded>
// manufacturer ----> maker <lower case>
// name ------------> item
// category & price-> details: -> Category, price, discounted_price <Discounted price by 10%>
// Also, the outputs are sorted by maker field
db.products.aggregate([
{
$project: {
@saintc0d3r
saintc0d3r / 1_insert.js
Last active August 29, 2015 14:03
[DRAFT] CRUD (Insert-Find-Update-Remove) in mongodb (using Mongo Shell)
// Let's say we have a store database
use store
// And we want to use store to keep our products information
db.products.insert({'brand': '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) })
db.products.insert({'brand': '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) })
db.products.insert({'brand': '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) })
db.products.insert({'brand': 'Zotac', 'category':'Desktop Graphics Card', 'description':'ZOTAC ZT-70301-10P GeForce GTX 770 2GB 256
@saintc0d3r
saintc0d3r / index_excercise_1.js
Last active August 29, 2015 14:03
Exercise 1 - Which Query that hit the indexes ?
// Let's say we have a store database where the database has products collection with several documents in it
use store
db.products.insert({'sku': '119-4567-7895', 'price':359.99, 'description': 'Intel Core i7-4770K Haswell Quad-Core 3.5GHz LGA 1150 84W Desktop Processor Intel HD Graphics BX80646I74770K', 'category':'CPU-Processors-Desktops', 'brand': 'Intel', 'reviews': [{'author': 'Mr.T', 'pros':"I play video game and I do video editiing. When it's time to compress movie and work on it, it's really fast.", 'cons': "The temperature is on the high side, but I think it's the way they run."}]})
db.products.insert({'sku': '121-6478-7234', 'price':374.99, 'description': 'ASUS GTX770-DC2OC-2GD5 GeForce GTX 770 2GB 256-Bit GDDR5 PCI Express 3.0 HDCP Ready SLI Support Video Card', 'category': 'Desktop Graphics Cards','brand': 'ASUS', 'reviews': [{'author': 'Slyder', 'pros':"Plug and play super fast works great so far nothing wrong with the way it's been working", 'cons':"Nothing yet"}]})
db.products.insert({'sku': '
@saintc0d3r
saintc0d3r / profiling.js
Created June 29, 2014 21:11
Profiling query in MongoDb
// There are 3 levels profilings in mongodb: Lvl 0, 1 & 2.
// Level 0: The profiler is turned off.
// Level 1: The profiler would log slow queries
// Level 2: The profiler would log all queries (good choice for development phase)
// The profiling's settings could be enabled by suppling certain parameters when starting mongod service.
// Here's the example: I want to start mongod & also enable level 1 profiling where it would log any queries that took 10 ms & more
mongod --profile 1 --slowms 10
// Suppose, we have 10000000 documents stored in bar collections (foo database)
@saintc0d3r
saintc0d3r / read_mongod_log.js
Created June 29, 2014 20:23
How identify a query's performance though reading Mongod's log
// Suppose, we have 10000000 documents stored in bar collections (foo database)
use foo
for(var i = 0; i< 10000000; i++)(db.bar.insert({'a':i, 'b':i, 'c':i}))
// Let's pretend that we have an application that accesses foo.bar and perform this query
db.bar.find({'a':506785})
// Now, we want to peek how long did the query finish its job through peeking the mongod's log
// Focus on the command line box that runs mongod. You should notice a line that similar to mine at below:
// 2014-06-30T04:13:08.193+0800 [conn1] query foobar.foo query: { a: 555666.0 } planSummary: COLLSCAN
@saintc0d3r
saintc0d3r / text_search_index.js
Created June 29, 2014 14:29
Text Search Index in MongoDB
// Let's say we have a documents db where it has a sentences collection
use documents
db.sentences.insert({'words': 'Cat moss granite.'})
db.sentences.insert({'words': 'dog tree ruby.'})
db.sentences.insert({'words': 'dog tree obsidian.'})
db.sentences.insert({'words': 'dog tree granite.'})
db.sentences.insert({'words': 'dog shrub ruby.'})
db.sentences.insert({'words': 'dog shrub obsidian.'})
db.sentences.insert({'words': 'dog shrub granite.'})
db.sentences.insert({'words': 'dog moss ruby.'})
@saintc0d3r
saintc0d3r / geospatial_spherical_index.js
Last active August 29, 2015 14:03
Geospatial Spherical Index in MongoDb
// Let's say , we have a geo database that has places collection in it
use geo
db.places.insert({'name': 'pepito', 'city': 'Badung, Bali', 'type': 'retail', 'location': {'type': 'Point', 'coordinates': [-8.738151,-25.1735585]}})
db.places.insert({'name': 'circle-k', 'city': 'Tuban, Bali', 'type': 'mini mart', 'location': {'type': 'Point', 'coordinates': [-8.7358627,-25.168867000000006]}})
db.places.insert({'name': 'ayunadi', 'city': 'Tuban, Bali', 'type': 'grocery', 'location': {'type': 'Point', 'coordinates': [-8.7394041,-25.1675752]}})
// Next, we'll put '2dsphere' index on the location field
// Caution: 2dsphere is limited to the range -180,180 for x coordinate/longitude, and -90,90 for y coordinate/latitude !
var index = {'location':'2dsphere', 'type':1, 'city':1}
db.places.ensureIndex(index)
@saintc0d3r
saintc0d3r / geospatial_index.js
Last active August 29, 2015 14:03
Geospatial Index In Mongodb
// Let's say , we have a geo database that has places collection in it
use geo
db.places.insert({'name': 'pepito', 'type': 'dept. store', 'location': [40, 70]})
db.places.insert({'name': 'circle-k', 'type': 'mini mart', 'location': [40.232, -74.343]})
db.places.insert({'name': 'ayunadi', 'type': 'grocery', 'location': [41.232, -75.343]})
// Next, we want to put an index on the location field.
// Since the location's value is the x-y coordinate of a place, we'll put '2d' index on it.
var index = {'location': '2d', 'type':1}
db.places.ensureIndex(index)