加载 JSON 字符串存储到 pyMongo

Loading a JSON string for storage into pyMongo

我正在使用 urllib 库打开一个 url 并读入数据。然后将数据转换为字符串,需要输入到pymongo中的一个集合中。我当前的代码如下:

import pymongo, urllib.request, json
from pymongo import MongoClient

reponse = urllib.request.urlopen('Website with JSON on it')
plstr = str(response.read())

module4 = MongoClient()

mycol= module4.payload

output = mycol.insert_one(plstr)

print(output.inserted_id)

我不知道如何在 JSON 中正确读取 MongoDB,所以我将其转换为字符串,但这不是解决问题所必需的。任何让 MongoDB 存储 JSON 数据的方法都很棒。谢谢

例如,您只需将文档传递给 insert_one()

import requests
import json
import pymongo

# You need a pymongo version > 3.0
print pymongo.version

r = requests.get('https://jsonplaceholder.typicode.com/posts/1')
your_document = json.loads(r.text) # let's suppose your_document is list of dicts 

# connection on the default host and port
client = pymongo.MongoClient()

# your db name
your_db = client.db_name

# your collection name
your_collection = your_db.collection_name

# let's suppose you want to load the first dict of the list
result = your_collection.insert_one(your_document[0]) 

# print the ObjectId of the inserted doc
print result.inserted_id 

来自文档:your_document 必须是可变映射类型。使用您刚从网站

收到的dict