Last active
December 12, 2015 01:18
-
-
Save k0emt/4689837 to your computer and use it in GitHub Desktop.
MongoDB, PyMongo example working with returned documents.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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