gpt4 book ai didi

mongodb - PyMongo 将 BSON 文档插入 MongoDB

转载 作者:行者123 更新时间:2023-12-02 18:25:40 26 4
gpt4 key购买 nike

我想将一个新文档插入到我的 MongoDB 集合中。

我的第一个输入是一个字符串,如下所示:

{
"date" : ISODate("2013-10-06T18:11:26.329Z"),
"engines" : {},
"expiration_date" : ISODate("2013-10-06T18:11:36.329Z"),
"file_name" : "elad.elad",
"scan_status" : "TEST",
"task_id" : "4ce4ae9e-ef0a-476a-8189-92a5bfe328bd"
}

我正在使用以下字符串创建一个 bson.BSON 对象:

b=bson.BSON(doc)

我正在尝试将其插入到我的 MongoDB 集合中:

collection.insert(b)

但我收到以下错误:类型错误:“str”对象不支持项目分配

有人知道这里出了什么问题吗?

最佳答案

您可以直接将字符串转换为 BSON,您需要 json.loadsBSON.encode 方法。

您可以使用以下代码:

import datetime
from pymongo import MongoClient

db = MongoClient().test
collection = db.some

doc = {
"date" : datetime.datetime.strptime("2013-10-06T18:11:26.329Z", "%Y-%m-%dT%H:%M:%S.%fz"),
"engines" : {},
"expiration_date" : datetime.datetime.strptime("2013-10-06T18:11:36.329Z","%Y-%m-%dT%H:%M:%S.%fz"),
"file_name" : "elad.elad",
"scan_status" : "TEST",
"task_id" : "4ce4ae9e-ef0a-476a-8189-92a5bfe328bd"
}
collection.insert(doc)

这里我使用 datetime 对象将字符串日期转换为 Python 兼容的日期时间

关于mongodb - PyMongo 将 BSON 文档插入 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31304085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com