📜  如何使用Python在 MongoDB 中导入 JSON 文件?

📅  最后修改于: 2022-05-13 01:55:46.938000             🧑  作者: Mango

如何使用Python在 MongoDB 中导入 JSON 文件?

先决条件: MongoDB 和Python,在Python中处理 JSON 数据

MongoDB 是一个跨平台的面向文档和非关系(即 NoSQL)的数据库程序。它是一个开源文档数据库,以键值对的形式存储数据。

JSON代表 JavaScript 对象表示法。它是一种开放的标准文件格式和扩展名为“.json”的数据交换格式,它使用人类可读的文本来存储和传输由属性值对和数组数据类型组成的数据对象。

在 MongoDB 中导入 JSON 文件

要在 MongoDB 中导入 JSON 文件,我们必须首先加载或打开 JSON 文件,然后我们可以轻松地将该文件插入到数据库或集合中。要加载 JSON 文件,我们必须首先在代码中导入json ,然后才能打开 JSON 文件。当我们的文件被加载或打开时,我们可以轻松地将其插入到集合中并对该文件进行操作。让我们看一下示例以便更好地理解。

例子 :

使用的示例 JSON:

python-mongodb-json

import json
from pymongo import MongoClient 
  
  
# Making Connection
myclient = MongoClient("mongodb://localhost:27017/") 
   
# database 
db = myclient["GFG"]
   
# Created or Switched to collection 
# names: GeeksForGeeks
Collection = db["data"]
  
# Loading or Opening the json file
with open('data.json') as file:
    file_data = json.load(file)
      
# Inserting the loaded data in the Collection
# if JSON contains data more than one entry
# insert_many is used else inser_one is used
if isinstance(file_data, list):
    Collection.insert_many(file_data)  
else:
    Collection.insert_one(file_data)

输出:

python-json-to-mongodb