使用pymongo将对象列表作为不同的Mongo文档插入

时间:2016-12-12 21:10:50

标签: python mongodb python-2.7 pymongo

我的dataset看起来像这样:

[{
    "myhost1.com": {
        "services": [
            {
                "environment": "prod", 
                "__module__": "polling_functions", 
                "serviceName": "service-a", 
                "__class__": "app"
            }
        ]
    }, 
    "myhost2.com": {
        "services": [
            {
                "environment": "prod", 
                "__module__": "polling_functions", 
                "serviceName": "service-a", 
                "__class__": "db"
            }
        ]
    }, 
    ...

我想要做的是在MongoDB中将每个文件作为单独的文档插入。在清除密钥以删除.个字符后,我尝试了两个插入:

db.hostuse.insert_many(dataset)

for key in dataset[0]:
    db.hostuse.insert_one(dataset[0][key])

这些都没有达到我想要的效果。第一个插入单个文档,键是主机名。第二个插入多个文档,但没有主机名;相反,每个键都是services

如何转换此数据集以便将其传递给MongoDB,并生成多个文档,每个文档的关键字为hostname

1 个答案:

答案 0 :(得分:1)

像这样:

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`grocery_supermarket_manager`.`#sql-9ac_8`, CONSTRAINT `AdministratorDepartment_FK` FOREIGN KEY (`id_department`) REFERENCES `department` (`id_department`) ON DELETE CASCADE ON UPDATE CASCADE)
SQL Statement:
ALTER TABLE `grocery_supermarket_manager`.`administrator` 
ADD CONSTRAINT `AdministratorDepartment_FK`
  FOREIGN KEY (`id_department`)
  REFERENCES `grocery_supermarket_manager`.`department` (`id_department`)
  ON DELETE CASCADE
  ON UPDATE CASCADE

您需要将dict从数据集[0]中拉出来,并且对于dict中的每个键和值,插入一个单独的文档。