Search This Blog

Thursday, December 26, 2013

Pymongo code example to manipulate data

Important note: This article is in relation to online MongoDB course. For more information about the course and other posts describing its content please check my main page here: M101P: MongoDB for Developers course

In the various files in week2 directory you are going to find extensive code examples how to use the pymongo module. Below is a quick and short summary of the most important functions. I hope all code is self explanatory.

query = {'type':'exam', 'score':{'$gt':50, '$lt':70}}
iter = scores.find(query)

query = {'type':'exam'}
selector = {'student_id':1, '_id':0}
iter = scores.find(query, selector)

query = {'student_id':10}
doc = scores.find_one(query)

counter = counters.find_and_modify(query={'type':name},
update={'$inc':{'value':1}},
upsert=True, new=True)

cursor = scores.find(query).limit(10).skip(30)

query = {'media.oembed.type':'video'}
projection = {'media.oembed.url':1, '_id':0}
iter = scores.find(query, projection)

doc = {"name":"Andrew Erlichson", "company":"10gen","interests":['running', 'cycling', 'photography']}
people.insert(doc)

things.update({'thing':'apple'}, {'$set':{'color':'red'}}, upsert=True)
things.update({'thing':'pear'}, {'color':'green'}, upsert=True)

scores.update({},{'$unset':{'review_date':1}},multi=True)

scores.find_one({'student_id':1, 'type':'homework'})
score['review_date'] = datetime.datetime.utcnow()
scores.save(score)

scores.update({'student_id':1, 'type':'homework'},
{'$set':{'review_date':datetime.datetime.utcnow()}})

cursor = cursor.sort([('student_id',pymongo.ASCENDING),('score',pymongo.DESCENDING)])

No comments:

Post a Comment