MongoDB for Developers – WEEK1

Leave a comment

October 15, 2016 by oneOokay

Oct 11, 2016

MongoDB Related:

  • sudo mongo/bin
  • create folder to store data:  /data/db #where mongo db stores its data
    • Some file operation commands
      • mkdir -p /data/db #mkdir -p creates nested directories only if they don’t exist already
      • chmod 777 /data #777 grant all rights
      • chmod 777 /data/db
  • Mongo engine: ./mongod #the real mongo db
  • Mongo shell: ./mongo #javascript tool to access mongo database
  • MongoDB supports Scalling out by its sharding feature

Commands:

  • show dbs
  • use : switch between databases.
  • db.foo.find(): this returns a cursor.
var c = db.foo.find() //returns a cursor
c.hasNext() //return true/false
c.next() //return a record/document
var j = db.foo.findOne()
j.key = value
db.foo.save(j)
  • db.foo.find().pretty() #output in a ‘pretty’ format
  • db.foo.find({key:value})
  • db.foo.findOne()
  • db.foo.insertOne({…})
  • db.foo.drop() #drop one collection
  • db.dropDatabase() # drop current database that you are using.
  • db is a reference to the database that we are currently using
  • restore database: mongorestore + database file path: file structure: dump/database/collections.bson

PyMongo sample code:

import pymongo
# from pymongo import MongoClient 
# so we dont need to type pymongo.MongoClient everytime
# connect to database
 connection = MongoClient('localhost', 27017) 
# connection = pymongo.MongoClient("mongodb://localhost")
 db = connection.test
# handle to names collection
 names = db.names
 item = names.find_one()
 print item['name'] #print the value of key 'name'

foo.insert_one(doc)

Document Oriented design : to embed OR not to embed

  • if they are accessed at the same time.
  • a mongo db document can be only less than 16 MB

Python:

  • readable
  • Garbage collected : dont need to worry about own memory management
  • dynamically typed
"stra" + "strb" = "strastrb"
list slices: a[start:end] start : inclusive; end: exclusive
a[2:]: from the index = 2 all the way to the end of the list
a[:4] from the begin of the list to the index = 3 element
a[:] return the entire list
a  = ['apple', 'pear']
len(a) : length of a list
List inclusion:
if 'apple' in a:
    print("there is an apple")
Dicts
colors = {'sky':'blue', 'sea':'blue','earth':'brown'}
JSON retains the order of the keys but python doesn't
Dicts & Lists
a = {'name':'ashin', 'interests':['cycling', 'running', 'golf']}
a['interests'][0]
a['interests'].append('swimming')

Function Calls:
def foo():
Exception Handling:
import sys
try:
XXX
except Exception as e:
print "exception: ", type(e), e

Bottle Related:

“Bottle” sample code: Example: “Hello World” in a bottle
http://bottlepy.org/docs/dev/index.html

*.tpl file in view folder

{{foo}} in tpl file to reference the value

%for ... %end inserts python code in tpl file

@bottle.route('/') ,  @bottle.route('/show_fruit')  # router

@bottle.post('/favorite_fruit') # a post router

bottle.redirect("/show_fruit") # redirect

return bottle.template('hello_world', {'username': "DDD", 'things': mythings}) # returns a webpage: hello_world.tpl file.

Cookies:

bottle.response.set_cookie("fruit", fruit)

fruit = bottle.request.get_cookie("fruit")

bottle.debug(True)
bottle.run(host = 'localhost', port = '8080')

JSON: example:

{
"headline" : "Apple Reported Fourth Quarter Revenue Today",
"date" : "2015-10-27T22:35:21.908Z",
"views" : 1132,
"author" : {
"name" : "Bob Walker",
"title" : "Lead Business Editor"
},
"published" : true,
"tags" : [
"AAPL",
{ "name" : "city", "value" : "Cupertino" },
[ "Electronics", "Computers" ]
]
}

BSON:
mongoDB stores data in BSON: Binary JSON.

// JSON
   { "hello" : "world" }
// BSON
"\x16\x00\x00\x00\x02hello\x00 
\x06\x00\x00\x00world\x00\x00"

Setup:

  • pip is not included in python 2.X. It is only included in python 3.X
  • install pip for MacOS: command: sudo easy_install python.
  • python version: python –version

Some random pieces:

  • MacOS: make yourself as root: sudo bash.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: