MongoDB - 打印 [英] MongoDB - Print
问题描述
我对打印一系列查询感兴趣.我有以下代码.
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.
我的问题是:
是否可以打印出整个查询的一个元素?例如,我希望它只打印项目或日期或插入的其他输入,而不是给我 {'time': datetime.datime(....), 'input1': ..., 'item': ...}.否则,如果我必须重新解析我已经解析的 mongodb 查询数据以放入 mongodb,这将大大减慢我的程序.
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.
谢谢.
推荐答案
让我们了解一下 pymongo 的工作原理.
Let's have some basics about how pymongo works.
假设您在 Mongo 中有一些带有插入数据的集合.您想通过查询从该集合中获取数据:
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}})
"model" 集合对象的方法 find 返回 Cursor
对象:一个包含有关查询和查询结果的所有信息的实体.
Method find of "model" collection object returns Cursor
object: an entity that holds all info about the query and query results.
于是查询完毕,下一步就是获取结果了.Mongo 查询的结果类型可能因方法而异.在我们的例子中(find
方法) - 结果是一堆 JSON 对象(迭代器对象),它们中的每一个都由 Python 语言中的 dict
类型表示.这意味着您不必解析结果:它们已经被解析为字典.
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.
关于Cursor
的另一件事:它是懒惰的.这意味着您可以按需获得结果.对于 Cursor
对象,您必须遍历它以获取使用查询获取的对象:
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>
通常,您必须尝试阅读 Pymongo 教程:它很短而且指示整个驱动程序的工作方式.
Generally, you have to try reading Pymongo Tutorial: it's quite short and gives direction of how the whole driver works.
这篇关于MongoDB - 打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!