Используя Python для вставки_one в мою mongo_db. Как передать значения ключей в функцию?Python

Программы на Python
Anonymous
Используя Python для вставки_one в мою mongo_db. Как передать значения ключей в функцию?

Сообщение Anonymous »

У меня была рабочая функция для вставки нового документа в мою базу данных, но я просмотрел свое задание и обнаружил, что в инструкциях нужна функция, принимающая аргументы, и когда я переписываю код, я получаю ошибку типа.
(рабочий код)
def create():

new_animal = {'animal_id': input('Enter animal_id'),
'rec_num': input('Enter rec_num'),
'age_upon_outcome': input('Enter age_upon_outcome')}
print(new_animal)

animals_collection = DbTools.db.animals

result = animals_collection.insert_one(new_animal)

document_id = result.inserted_id
print(f"_id of inserted document: {document_id}")
print(new_animal)

document_to_find = {'_id': ObjectId(document_id)}
result = animals_collection.find_one(document_id)
print("Found :", document_id)
print(result)

переписал это, чтобы соответствовать требованиям назначения.
"Входной аргумент функции будет набором пар ключ/значение в типе данных, приемлемом для вызова API вставки драйвера MongoDB. "
(Main.py)
import CRUD

CRUD

new_animal = {
'animal_id': input('Enter animal_id'),
'rec_num': input('Enter rec_num'),
'age_upon_outcome': input('Enter age_upon_outcome')}

for key,val in new_animal.items():
CRUD.DbTools.create(key,val)

(CRUD.py)
def create(key, value):

new_animal = {key, value}
print(new_animal)

animals_collection = DbTools.db.animals

result = animals_collection.insert_one(new_animal)

document_id = result.inserted_id
print(f"_id of inserted document: {document_id}")
print(new_animal)

document_to_find = {'_id': ObjectId(document_id)}
result = animals_collection.find_one(document_id)
print("Found :", document_id)
print(result)

Выход:
Pinged your deployment. You successfully connected to MongoDB!
Enter animal_id111
Enter rec_num222
Enter age_upon_outcome333
{'111', 'animal_id'}
Traceback (most recent call last):
File "/Users/CS340WS/Main.py", line 28, in
CRUD.DbTools.create(key,val)
File "/Users/CS340WS/CRUD.py", line 34, in create
result = animals_collection.insert_one(new_animal)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/CS340WS/venv/lib/python3.11/site-packages/pymongo/collection.py", line 663, in insert_one
common.validate_is_document_type("document", document)
File "/Users/CS340WS/venv/lib/python3.11/site-packages/pymongo/common.py", line 552, in validate_is_document_type
raise TypeError(
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

Я также написал это, чтобы упростить то, что пытался сделать.
import sys
import test2

new_animal = {
'animal_id': input('Enter animal_id'),
'rec_num': input('Enter rec_num'),
'age_upon_outcome': input('Enter age_upon_outcome')}

for key,val in new_animal.items():
test2.i.this(key,val)

class i:
def this(key, value):

new_animal = {key, value}
print(new_animal)

Выход:
Enter animal_id111
Enter rec_num222
Enter age_upon_outcome333
{'111', 'animal_id'}
{'rec_num', '222'}
{'age_upon_outcome', '333'}


Подробнее здесь: https://stackoverflow.com/questions/782 ... to-a-funct

Вернуться в «Python»