Skip to content

Instantly share code, notes, and snippets.

@vgoklani
Forked from newitfarmer/MongodbExample.py
Created January 3, 2012 18:37
Show Gist options
  • Save vgoklani/1556229 to your computer and use it in GitHub Desktop.
Save vgoklani/1556229 to your computer and use it in GitHub Desktop.
from pymongo import Connection
import datetime
import time
#connect to mongodb
connection = Connection(‘newitfarmer.com’, 27017)
# get database
db = connection.test_database
#get one collection
collection = db.test_collection
post = {“author”: “Mike”,”text”: “My first blog post!”,”tags”: ["mongodb", "python", "pymongo"],”date”: datetime.datetime.utcnow()}
posts = db.posts
#insert one recorder
posts.insert(post)
#get one recorder
posts.find_one()
posts.find_one({“author”: “Mike”})
#Bulk Inserts
new_posts = [{"author": "Mike","text": "Another post!","tags": ["bulk", "insert"],”date”: datetime.datetime(2009, 11, 12, 11, 14)},{“author”: “Eliot”, “title”: “MongoDB is fun”,”text”: “and pretty easy too!”,”date”: datetime.datetime(2009, 11, 10, 10, 45)}]
posts.insert(new_posts)
#insert large amount data
index=0
start = time.time()
for i in range (0,1000000):
post = {“author”: “Mike”,”text”: “My first blog post!”,”tags”: ["mongodb", "python", "pymongo"],”date”: datetime.datetime.utcnow()}
#posts.insert(post)
index=index+1
if index % 1000 == 0 :
print “inserted %d post” %index
print “inserted %d post totally” %index
print “Elapsed Time: %s” % (time.time() – start)
start = time.time()
index=0
for post in posts.find():
posts.remove(post)
index=index+1
if index % 1000 == 0 :
print “remove %d post” %index
print “removed %d post totally” %index
print “Elapsed Time: %s” % (time.time() – start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment