【问题标题】:Insert Multiple JSON files to MongoDB using python使用 python 将多个 JSON 文件插入到 MongoDB
【发布时间】:2020-04-17 08:01:57
【问题描述】:

JSON文件如下a.json,b.json.....z.json(26个json文件)

每个文件的json格式如下:

{
    "a cappella": {
        "word": "a cappella",
        "wordset_id": "5feb6f679a",
        "meanings": [
            {
                "id": "492099d426",
                "def": "without musical accompaniment",
                "example": "they performed a cappella",
                "speech_part": "adverb"
            },
            {
                "id": "0bf8d49e2e",
                "def": "sung without instrumental accompaniment",
                "example": "they sang an a cappella Mass",
                "speech_part": "adjective"
            }
        ]
    },
    "A.D.": {
        "word": "A.D.",
        "wordset_id": "b7e9d406a0",
        "meanings": [
            {
                "id": "a7482f3e30",
                "def": "in the Christian era",
                "speech_part": "adverb",
                "synonyms": [
                    "AD"
                ]
            }
        ]
    },.........
}

如何将这些存储在 MongoDB 中,这样如果使用 word 查询,结果会显示 meanings,synonyms(如果可用)?

我从未使用过 Mongo 来处理方法,但对于 mysql 中的单个 json 文件的 SO 建议也是如此:

**游标有数据库连接

with open('a.json') as f:
    d = json.load(f)

for word in d:
    word_obj = d[word]
    wordset_id = word_obj['wordset_id']

    sql = "INSERT INTO Word (word, wordset_id) VALUES (%s, %s)"
    values = (word, wordset_id)
    cursor.execute(sql, values)
    conn.commit()

类似于将含义和同义词存储为不同的表,

但正如我建议的那样,如果使用 MongoDB,我想这会变得更好

【问题讨论】:

  • 抱歉,“我从未使用过 Mongo”只是请求提供有关该主题的教程。先通过那个。然后,尝试在 Python 中复制这些东西。 Stack Overflow 无法从头开始教你东西,它也不想教。
  • 有道理,我可以连接到 mongo ,但正在寻找一次插入所有 json 文件的方法,感谢您的建议
  • 看起来你使用的是SQL而不是MongoDB
  • 是的,我用 sql 试过了,我也想用 mongo 复制

标签: python mongodb pymongo


【解决方案1】:

如果要从多个.json 文件中插入数据,请循环执行:

file_names = ['a.json', 'b.json', ...]

for file_name in file_names:
    with open(file_name) as f:
        file_data = json.load(f)  # load data from JSON to dict
        for k, v in file_data.items():  # iterate over key-value pairs
            collection.insert_one(v)  # your collection object here

【讨论】:

  • 当我只是尝试使用 a.json 单个文件作为测试时,它抛出了一个错误:bson.errors.InvalidDocument: key 'A.D.'不得包含“.” (此数据在上述问题中)
  • 在 mongo 中,key 不能包含. 字符。如果您的文件仅在顶层包含 . ,那没关系,因为它们没有插入到集合中(在我的示例答案中)。否则,您应该更改键名。
  • 不,因为. 在他们的查询语言中使用,例如key1.key2
  • 嗯,有时人们只是将. 替换为_。如果您将来需要将密钥“恢复”为“原始”格式并避免与真正的“_”字符发生冲突,您可以使用自己的自定义字符序列对. 进行编码。比如双下划线什么的。
  • 您在上面写的内容听起来与表分区完全一样。我没有在 Mongo 中使用过这个功能,但你可以用谷歌搜索。我没有关于您的应用程序功能的详细信息,因此分区可能不是您可以使用的最有效的技巧。
猜你喜欢
  • 1970-01-01
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 2013-12-13
  • 2018-09-05
  • 2013-07-25
相关资源
最近更新 更多