2017-09-26 69 views
0

我用的MongoDB和PyMongo工作,我想通過ID刪除行:bson.errors.InvalidId pymongo

_id = "c8c9447c42c82044be595b" #row id in database 
result = database.collection.delete_one({"_id": ObjectId(_id)}) #delete one row with the given id 
print(result.deleted_count) #1 true, 0 false 

當我運行我的代碼,我得到了以下錯誤消息:

bson.errors.InvalidId: 'c8c9447c42c82044be595b' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string 

我已經嘗試過我的ID轉換爲十六進制,但它沒有工作,還是同樣的錯誤

hexlify = codecs.getencoder('hex') 
print(':'.join(hex(ord(x))[2:] for x in 'c8c9447c42c82044be595b')) 

有什麼建議?

+0

您是否嘗試先導入ObjectId?像 - 從bson.objectid導入ObjectId –

+0

是的,我已經導入>>從bson import ObjectId – tamaramaria

回答

1

如消息所示,'c8c9447c42c82044be595b'不是有效的ObjectId:它必須是12字節輸入或24字符的十六進制字符串。您只提供了22個字符。 =)