JGuizard
6/16/2016 - 7:46 AM

Example of use of MongoDB in python with pymongo

Example of use of MongoDB in python with pymongo

#./bin/mongod --dbpath=./data

import pymongo
cli = pymongo.MongoClient('mongodb://localhost:27017')

#drop the table
#cli.testdb.babies.drop()
import csv
with open('babynames.csv','rb') as csvfile:
    babies = csv.reader(csvfile)
    next(babies)
    for row in babies:
        cli.testdb.babies.insert({'year': row[0],
                                 'firstname':row[1],
                                 'country':row[2],
                                  'sex':row[3],
                                  'count':row[4]})
#./bin/mongod --dbpath=./data

from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
client.phonebook.collection_names()
db=client.phonebook
col=db.people

cmd=''
while(cmd!='exit'):
	cmd=raw_input("Joe: ")
	if(cmd=='show'):
		people=col.find()
		for person in people:
			print person
	elif(cmd=='insert'):
		name=raw_input("Name: ")
		phone=raw_input("Phone: ")
		node=input("Node: ")
		col.insert({'name':name,'phone':phone},w=node,j=False)	#w=0, write data asyncronous, 
	elif(cmd=='remove'):
		name=raw_input("Name: ")
		col.remove({"name": name})
	elif(cmd=='destroy'):
		col.remove()
	elif(cmd=='update')
		name=raw_input("Name: ")
		phone=raw_input("Phone: ")
		#This will replace the entry without store the last field
		#col.update({'name':name},{name'phone':phone})
		col.update({'name':name},{'$set':{'phone':phone}})
	elif(cmd!='exit'):
		print "Unknown command"

"""
	#find return a cursor, it work like a generator
	cursor=col.find()
	#return next element
	next(cursor)
	#return the cursor as a list of dict
	list(cursor)

	#advanced search query
	col.find_one({'name':'Giuseppe'},)
	#find all entries with id greater than OBJ_ID
	list(col.find({'_id':{'$gt':bson.ObjectId('OBJ_ID')}}))

	#find all entries with name that start with O using regex
	list(col.find({'name':{'$regex':'^O'}}))

	#Other way to update
	doc=col.find_one({'name':'Giuseppe'})
	doc['phone']='12345'
	col.save(doc) #or col.update({'name':'Giuseppe'},doc)
	
	#Drop a table
	#drop the table
  #client.testdb.babies.drop()