Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MongoDB, PyMongo example working with returned documents.
from pymongo import MongoClient
import pymongo
import sys
# establish a connection to the database
connection = MongoClient("mongodb://localhost", safe=True)
# get a handle to the school database
db = connection.school
scores = db.scores
def find_skip_limit_sort_demo():
query = {}
counter = 0
try:
cursor = scores.find(query).skip(4)
cursor = cursor.limit(5)
# cursor = cursor.sort('student_id', pymongo.ASCENDING).skip(4).limit(1)
cursor = cursor.sort([('student_id', pymongo.ASCENDING), ('score', pymongo.DESCENDING)])
except:
print "Unexpected error:", sys.exc_info()[0]
for doc in cursor:
my_doc = doc
counter += 1
my_doc['added'] = counter
print my_doc['student_id'], my_doc['type'], my_doc['score'], my_doc['added']
# or
doc['added'] = counter
print doc['student_id'], doc['type'], doc['score'], doc['added']
find_skip_limit_sort_demo()
connection.disconnect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.