这听起来像是一个愚蠢的问题,但我正在使用 pymongo 并编写了以下函数来插入文档,并且想知道 insert_many 方法是否也适用于一条记录插入,这样我就不需要另一个函数了我只是插入一条记录。
这是我的功能:
def insert_records(list_of_documents: list, collection):
i = collection.insert_many(list_of_documents)
print(len(i.inserted_ids), " documents inserted!")
当我插入一个时,它会抛出错误:
post1 = {"_id":0, "user_name":"Jack"}
insert_records(list(post1), stackoverflow)
TypeError:文档必须是 dict、bson.son.SON、bson.raw_bson.RawBSONDocument 的实例,或者继承自 collections.MutableMapping 的类型
我知道我可以使用 insert_one() 来达到此目的,我只是想知道是否可以使用 insert_many() 完成所有操作,因为原始的 insert() 方法已被弃用。谢谢!
最佳答案
由于您的 post1
是一个字典,当您使用 list(post1)
时,您有一个键列表:
>>> list(post1)
['_id', 'user_name']
使用:
>>> [post1]
[{'_id': 0, 'user_name': 'Jack'}]
所以:
insert_records([post1], stackoverflow)
关于python - Pymongo 是否可以使用 insert_many 插入一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71360852/