Skip to main content

MongoDB example using pymongo on Linux


1. Install Mongodb
     #yum install mongodb
     #yum install mongodb-server

2. Install pymongo

3. Sample Script





from pymongo import Connection
import datetime
import time
import os, sys
reload(sys)
sys.setdefaultencoding("latin1")

connection = Connection("localhost", 27017)

db = connection.sample_db


#Insert a record on a table (sample_tb)

post = {"author": "Mike","text": "My first blog post!","tags": ["mongodb", "python", "pymongo"],"date": datetime.datetime.utcnow()}

posts = db.sample_tb

posts.insert(post)



#Select a record on a table (sample_tb)

posts = db.sample_tb

posts.find_one()

posts.find_one({"author": "Mike"})


for post in posts.find():
 print post['author']



#Delete a record on a table (sample_tb)

posts = db.sample_tb

posts.remove({"author": "Mike"})

Comments