首页 > 解决方案 > 提取mongodb文档并在python中创建json文件

问题描述

我有 mongodb 文档作为数组,需要在 python 中创建 json 文件。

mongodb文档看起来像

db.mappedfields.insertMany(
[ 
    { 
        sourceAttribute: "first_name",
        domainAttribute: "First_Name"
    },
    {
        sourceAttribute: "last_name",
        domainAttribute: "Last_Name"
    }
]

) 代码尝试

myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient["guid"]
mycol = mydb["mappedfields"]
cursor = mycol.find({},{'_id':False})
list_cur = list(cursor)
json_data = dumps(list_cur, indent=1)
with open('mapping_files/mapping_from_mongodb.json', 'w') as file:
    file.write(json_data)

获取输出

[
 {
  "sourceAttribute": "first_name",
  "domainAttribute": "First_Name"
 },
 {
  "sourceAttribute": "last_name",
  "domainAttribute": "Last_Name"
 }
]

预期输出:

{
    "first_name": "First_Name",
    "last_name": "Last_Name"
}

标签: pythonjsonmongodbmappingpymongo

解决方案


推荐阅读