可以使用insert_many()方法将多个文档写入到MongoDB集合中。
示例代码:
from pymongo import MongoClient
client = MongoClient()
db = client['my_db']
collection = db['my_collection']
# new documents to be added to the collection
new_docs = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 35}
]
# insert the new documents into the collection
result = collection.insert_many(new_docs)
# print the object ids of the new documents
print(result.inserted_ids)
此代码将添加三个新文档到名为my_collection的MongoDB集合中。insert_many()方法将多个文档传递给MongoDB服务端以一次性插入。inserted_ids属性返回插入文档的对象ID。