Как вставить данные TXT в Mongodb с помощью Python - PullRequest
0 голосов
/ 28 мая 2019

Мне нужно вставить данные из file.txt в новую коллекцию MongoDB database.collection с использованием python.

.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,';') и добавить его в Mongo с помощью insert_many, но я получаю эту ошибку

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)

Ответы [ 2 ]

1 голос
/ 28 мая 2019

collection.insert_many () ожидает список dict, просто загрузив содержимое txt-файла в строку и разделив на «;», вы получите список строк, таких как

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

Иpymongo / mongodb не позволяет вставлять строки, он ожидает документы (python dict's)

См. ниже (используется 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,...

Что вам нужно сделать, это загрузить строку в dict:

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"}')

0 голосов
/ 28 мая 2019

Большое спасибо, мне удалось вставить данные в 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)
...