【问题标题】:How to insert txt data into mongodb using python如何使用python将txt数据插入mongodb
【发布时间】:2019-05-29 04:18:14
【问题描述】:

我需要使用 python 将 file.txt 中的数据插入到新的 MongoDB database.collection 中。

.txt 文件包含如下数据:

a={
    "_id"          : "67a2c0e2e559fb56bf055502",
    "field1"       : "value1",
    "field2" : ["value21","value22"],
    "field3"  : {
                       "_id"  : "37a2c0e2e559fb56bf055502",
                       "subfield1" : "subvalue1"
                     }
};

b={
    "_id"          : "67a2c0e2e559fb56bf055503",
    "field1"       : "value1",
    "field2" : ["value21","value22"],
    "field3"  : {
                       "_id"  : "27a2c0e2e559fb56bf055503",
                       "subfield1" : "subvalue1"
                     }
};

c={....
};

如果我们说 a=doc1, b=doc2, C=doc3, d...,我想插入所有文档 我尝试使用 l=split(read,';') 将它们拆分到列表中,并使用 insert_many 将其添加到 Mongo,但出现此错误

TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

有什么方法可以在不创建 json 文件的情况下插入数据? 谢谢

代码

def insert():
    client = pymongo.MongoClient(dbStringConnection)

    db = client[dbName]

    collectionR = db[dbCollection]

    list1 = []
    with open (file, 'r') as f:
        reader= f.read()
        #print (reader)
    f.close()
    reader= reader.replace('\n', '')
    reader= reader.replace('  ','')
    list1 = reader.split(';')
   # print(list1[0])

    list2={}

    for i in range(len(lista)-1):

        s=''
        t=list1[i][0:1]
        s=s+str(list1[i][2:len(list1[i])])
        list2[t]=s
    collectionR.insert_many(list2)

【问题讨论】:

  • 你能显示你正在运行的确切代码吗?

标签: python pymongo


【解决方案1】:

collection.insert_many() 需要一个 dict 列表,通过简单地将 txt 文件的内容加载到一个字符串中并在 ";" 上拆分,您可以获得一个字符串列表,如

'a={ "_id" : "67a2c0e2e559fb56bf055502", "field1" : "value1", "field2" : ["value21","value22"], "field3" : { "_id" : "37a2c0e2e559fb56bf055502", "subfield1" : "subvalue1" } }'

而且 pymongo/mongodb 不允许您插入字符串,它需要文档(python dict)

见下文(使用insert_one,但原理与insert_many相同):

s = 'a={ "_id" : "67a2c0e2e559fb56bf055502", "field1" : "value1", "field2" : ["value21","value22"], "field3" : { "_id" : "37a2c0e2e559fb56bf055502", "subfield1" : "subvalue1" } }'
c.insert_one(s)   # raise TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument,...

您需要实现的是将字符串加载到字典中:

dic = { "_id" : "67a2c0e2e559fb56bf055502", "field1" : "value1", "field2" : ["value21","value22"], "field3" : { "_id" : "37a2c0e2e559fb56bf055502", "subfield1" : "subvalue1" } }
c.insert_one(dic)

如果您设法将 'a={"key1":"value1", "key2":"value2"}' 之类的字符串转换为 '{"key1":"value1", "key2:value2" 之类的字符串}',那么您可以使用eval 将字符串转换为带有my_dict=eval('{"key1":"value1", "key2":"value2"}') 的字典

【讨论】:

    【解决方案2】:

    非常感谢,我能够在 MongoDB 中插入数据

    def insert():
        client = pymongo.MongoClient(dbStringConnection)
    
        db = client[dbName]
    
        collectionR = db[dbCollection]
    
        list1 = []
        with open (file, 'r') as f:
            reader= f.read()
    
        f.close()
        reader= reader.replace('\n', '')
        reader= reader.replace('  ','')
        list1 = reader.split(';')
        for i in range(len(list1)-1):
            my_dict={}
            my_dict=eval((list1[i][2:len(list1[i])]))
            collectionR.insert_one(my_dict)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 2021-02-13
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      相关资源
      最近更新 更多