Skip to content

Instantly share code, notes, and snippets.

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 =
scores = db.scores
def find_skip_limit_sort_demo():
query = {}
counter = 0
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)])
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']
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.