MongoDB - Print

ぐ巨炮叔叔 提交于 2019-12-12 00:17:02

问题


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.


回答1:


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:

cursor = db.model.find({'time': {'$gte': start, '$lt': end}})

Method find of "model" collection object returns Cursor object: 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 (find method) - result is a bunch of JSON objects (iterator object), each of them is represented by dict type 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 of Cursor object, you must iterate through it to get object fetched with query:

for result_object in cursor:
    print result_object   # result_object is a dict that holds JSON object
    result_object['_id']  # Mongo ObjectId of the result_object
    # result_object["<field_name>"]  # Value stored in a field named <fieldname>

Generally, you have to try reading Pymongo Tutorial: it's quite short and gives direction of how the whole driver works.



来源:https://stackoverflow.com/questions/11958195/mongodb-print

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!