The sample DB for this post :
import pymongo
from datetime import *
client = pymongo.MongoClient("localhost", 27017)
#Create of get the DB
db = client['test-database']
#create user collection
userCollection = db['userCollection']
for nextNo in range (1,10,2):
new_user = {"Name":"zvika",
"Age":42,
"Childs":["Lior","Gal","Shahf"],
"dateofbirth" : datetime(1970, 10, 25),
"email" : "loveme42@hotmail.com",
"RunningNo":nextNo ,
"Blog address":"http://zvikastechnologiesblog.blogspot.com"}
userCollection.save (new_user)
Limiting the returned fields from mondo db results :
Return only the age and email fields :
users = db.userCollection.find({"Name":"zvika"},{"Age":1,"email":2})
for user in users:
print ( type ( user))
print ( user)returns:<class 'dict'>
{'_id': ObjectId('519ddd10def1c122d4074eef'), 'email': 'loveme42@hotmail.com', 'Age': 42}Add sorting users = db.userCollection.find({"Name":"zvika"},{"RunningNo":1,"email":2},sort=[("RunningNo", pymongo.DESCENDING)])
Limiting the resutls setusers = db.userCollection.find({"Name":"zvika"},{"RunningNo":1,"email":2},sort=[("RunningNo", pymongo.DESCENDING)]).limit(1)
Note:the result set limitation in this case is relevant to the sorted field in this case if there is a several documents with the same sorted value than all of them will return.for an example after running the sample data five times the result of the query will be :
<class 'dict'>
{'email': 'loveme42@hotmail.com', '_id': ObjectId('519de196def1c115a050470f'), 'RunningNo': 9}
<class 'dict'>
{'email': 'loveme42@hotmail.com', '_id': ObjectId('519de196def1c115a050470f'), 'RunningNo': 9}
<class 'dict'>
{'email': 'loveme42@hotmail.com', '_id': ObjectId('519de196def1c115a050470f'), 'RunningNo': 9}
<class 'dict'>
{'email': 'loveme42@hotmail.com', '_id': ObjectId('519de196def1c115a050470f'), 'RunningNo': 9}
<class 'dict'>
{'email': 'loveme42@hotmail.com', '_id': ObjectId('519de196def1c115a050470f'), 'RunningNo': 9}
The same result will be applied to limit 1..5 only if the limit will be greater then 6 the next batch will be returned.
The limit parse could be write although in the following syntex:
users = db.userCollection.find({"Name":"zvika"},{"RunningNo":1,"email":2},sort=[("RunningNo", pymongo.DESCENDING)] ,limit=24)
הבלוג שלי מכיל פרסומים של ההתעסקות המקצועית היום יומית שלי שלי בתור ארכיטקט ומוביל טכנולוגיות
יום שישי, 24 במאי 2013
MongoDB Queries cont
הירשם ל-
תגובות לפרסום (Atom)
אין תגובות:
הוסף רשומת תגובה