Python 如何从mongodb获取对象id

Python 如何从mongodb获取对象id,python,mongodb,Python,Mongodb,我想使用python从mongoDB获取文档,我可以获取所有属性,但我只想获取其对象id并将其存储到变量中 我正在尝试下面的代码 from pymongo import Connection from bson.objectid import ObjectId connection = Connection() server="localhost" port = 27017 connection =Connection(server , port) db = conn

我想使用python从mongoDB获取文档,我可以获取所有属性,但我只想获取其对象id并将其存储到变量中

我正在尝试下面的代码

from pymongo import Connection
from bson.objectid import ObjectId


connection = Connection()
server="localhost"
port = 27017

connection =Connection(server , port)

db = connection.flipkart

connection = db.flipitems

connection.remove({'name':None})

for post in connection.find():
    print post['_id':'ObjectId']
    seller_name = post['seller_name']
    name = post['name']
但它给出了以下错误

shubham@shubham-pc:~/Desktop/python$python fetch\u data.py回溯

(最后一次调用):文件“fetch_data.py”,第18行,在

print post['_id':'ObjectId'] TypeError: unhashable type
你可以简单地使用

    print str(post['_id'])
这将以字符串格式提供ObjectId


print post[''u id']
将objectId作为objectId('123456789023456')本身返回

如果您在
post['u id':'objectId']
中出错,您应该执行以下操作之一:

print post['_id']


如果你打印帖子,你会得到什么?你想要它作为objectId还是字符串?然后它会给整个文档(行)一个idtry
print post[id]
print post[\u id]
@ArunK我想再次使用它作为更新文档的id的比较。那么,哪个字符串或ObjectId更好呢?
print post['ObjectId']