[英]How do I find the name (key) of values in a collection while it's being iterated through using PyMongo?
When using a cursor to iterate through a collection like so, 当使用游标像这样遍历集合时,
import pymongo
cursor = pymongo.Connection().test_db.test_collection.find()
for item in cursor:
print item
#this will print the item as a dictionary
only the values are returned. 仅返回值。 I'm looking for a way to access the name of the value.
我正在寻找一种访问值名称的方法。
I have found a similar method called getCollectionNames() however it is used to return every collection name in the database. 我发现了一个类似的名为getCollectionNames()的方法,但是它用于返回数据库中的每个集合名称。
Quick [Hacky] Fix: Store the name of the collection inside the collection itself and simple call the name from the value returned by the cursor using item.name 快速[Hacky]修复:将集合名称存储在集合本身内部,并使用item.name简单地从光标返回的值中调用名称。
If I understand correctly, you are looking for a way to get the collection name you are working on or that you have queried; 如果我理解正确,那么您正在寻找一种方法来获取您正在使用或已查询的集合名称; If that is the case here is how you do it: user collection.name
如果是这样,请按照以下步骤操作:user collection.name
import pymongo
cursor = pymongo.Connection().test_db.test_collection.find()
print cursor.collection.name
for item in cursor:
print item
#this will print the item as a dictionary
If you mean to retrieve the keys inside of the collection itself. 如果您要检索集合本身内部的键。 You can simply add an extra loop and retrieve the keys for each document in cursor.
您可以简单地添加一个额外的循环并检索光标中每个文档的键。 example:
例:
import pymongo
cursor = pymongo.Connection().test_db.test_collection.find()
print cursor.collection.name
for item in cursor:
for key in item:
print key
You can iterate over the top level field names and their associated values using this snippet: 您可以使用以下代码片段访问顶级字段名称及其关联的值:
for fieldname, fieldvalue in item.iteritems():
print (fieldname, fieldvalue )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.