I am interested in printing a range of query. I have the following code.
start = datetime.datetime(2012, 2, 2, 6, 35, 6, 764)
end = datetime.datetime(2012, 2, 2, 6, 55, 3, 381)
for doc in db.model.find({'time': {'$gte': start, '$lt': end}}):
print doc
It does the job, printing out basically how I inserted the data.
My question is this:
Is it possible to print out one element of the whole query? Such as, I want it to only print the item or the date or another input inserted, not give me {‘time’: datetime.datime(….), ‘input1’: …, ‘item’: …}. Otherwise, it would greatly slow my program if I had to reparse the mongodb query data I have already parsed to put into mongodb.
Thank you.
Let’s have some basics about how pymongo works.
Let’s assume you have some collection in Mongo with inserted data. You want to get data from that collection by making queries:
Method find of “model” collection object returns
Cursorobject: an entity that holds all info about the query and query results.So the query is made, and the next step is getting results. Result types of Mongo queries can differ from method to method. In our case (
findmethod) – result is a bunch of JSON objects (iterator object), each of them is represented bydicttype in Python language. It means that you don’t have to parse results: they are already parsed into dicts.Another thing about
Cursor: it is lazy. It means that you receive results on demand. In case ofCursorobject, you must iterate through it to get object fetched with query:Generally, you have to try reading Pymongo Tutorial: it’s quite short and gives direction of how the whole driver works.