在find()之后如何将ObjectId转换为字符串?

时间:2020-09-04 12:50:26

标签: python mongodb pymongo

我有一个movies集合中的对象的示例:

{
    "_id":{"$oid":"5f5101c31a05d8a343f944b1"},
    "title":"Mother to Earth",
    "year":2020,
    "description":"A group of simps tries to find the source of an obscure meme game.",
    "screenings":
        [
            {
                "screeningID":{"$oid":"5f5101c31a05d8a343f944b0"},
                "timedate":"2020-09-29, 18:00PM",
                "tickets":46
            }
        ]
}

我希望这是一个find()函数的输出,并以title作为查询。但是,当我包含_idscreeningID时,会出现TypeError: Object of type ObjectId is not JSON serializable错误。我需要screeningID的值,以便在代码的后面部分使用它,最好将其用作string。我该怎么办?

编辑:这是有问题的两行代码:

result = movies.find_one({'title':data['title']})
result = {'title': result['title'],"year": result['year'],'description': result['description'],'screenings': [result['screenings']]}

为简单起见,我跳过了其中的条件检查。照原样,这会产生我上面显示的错误。唯一的解决方案是在第一行的投影中添加{'_id':0, 'screenings.screeningID':0},但这意味着丢失ObjectId,尤其是screeningID,这是我以后需要的。

1 个答案:

答案 0 :(得分:0)

我运行了您的代码,没有错误。如果您运行此程序,是否会遇到任何错误?

from pymongo import MongoClient
from bson import ObjectId

data = {
    "_id": ObjectId("5f5101c31a05d8a343f944b1"),
    "title":"Mother to Earth",
    "year":2020,
    "description":"A group of simps tries to find the source of an obscure meme game.",
    "screenings":
        [
            {
                "screeningID": ObjectId("5f5101c31a05d8a343f944b0"),
                "timedate":"2020-09-29, 18:00PM",
                "tickets":46
            }
        ]
}

db = MongoClient(port=27019)['testdatabase']
db.testcollection.delete_many({})

db.testcollection.insert_one(data)

result = db.testcollection.find_one({'title':data['title']})
result = {'title': result['title'],"year": result['year'],'description': result['description'],'screenings': [result['screenings']]}