首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用python将txt数据插入到mongodb中

如何使用python将txt数据插入到mongodb中
EN

Stack Overflow用户
提问于 2019-05-29 03:36:20
回答 2查看 846关注 0票数 1

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

.txt文件包含如下数据:

代码语言:javascript
运行
复制
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中,但是我得到了这个错误

代码语言:javascript
运行
复制
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

有没有办法在不创建json文件的情况下插入数据?谢谢

代码

代码语言:javascript
运行
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-29 03:49:58

collection.insert_many()需要一个字典列表,只需将txt文件的内容加载到一个字符串中并拆分";",就可以获得一个字符串列表,如下所示

代码语言:javascript
运行
复制
'a={ "_id" : "67a2c0e2e559fb56bf055502", "field1" : "value1", "field2" : ["value21","value22"], "field3" : { "_id" : "37a2c0e2e559fb56bf055502", "subfield1" : "subvalue1" } }'

pymongo/mongodb不允许你插入字符串,它需要文档(python Dict)

如下所示(使用insert_one,但原理与insert_many相同):

代码语言:javascript
运行
复制
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,...

您需要完成的是将字符串加载到字典中:

代码语言:javascript
运行
复制
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"}')将字符串转换为字典

票数 1
EN

Stack Overflow用户

发布于 2019-05-29 04:18:14

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

代码语言:javascript
运行
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56348992

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档