빅데이터/nosql
pymongo - find결과로 나온 데이터의 ObjectId()를 string으로 변경하기
AndersonChoi
2020. 5. 13. 14:14
def getSpecificId(id):
result = objectIdDecoder(list(collection.find({"_id": ObjectId(id)})))
return str(result)
def objectIdDecoder(list):
results=[]
for document in list:
document['_id'] = str(document['_id'])
results.append(document)
return results
pymongo를 통해 collection을 find한 다음 받은 ObjectId는 유효한 json type이 아니다. 그러므로 json형태로 사용할 경우에는 ObjectId를 String으로 변환하는 작업을 해야합니다.
이때 ObjectIdDecoder가 List형태의 array를 받아서 _id key를 str형태로 변경하는 로직의 method를 사용하면 편리하게 변경하여 json으로 사용할 수 있습니다.
반응형