我想使用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_data.py Traceback
(最近一次呼叫最后一次):文件" fetch_data.py",第18行,
print post['_id':'ObjectId'] TypeError: unhashable type
答案 0 :(得分:1)
您只需使用
即可 print str(post['_id'])
这将以字符串格式提供ObjectId
print post['_id']
会将objectId作为ObjectId('123456789023456')返回
答案 1 :(得分:0)
post['_id':'ObjectId']
你错了,你应该这样做:
print post['_id']
或
print post['ObjectId']