Python MongoDB:如何删除具有特定值的文档并将其插入到另一个集合中?

2023-04-15 00:00:00 集合 删除 插入

要删除具有特定值的文档并将其插入到另一个集合中,可以使用以下步骤:

  1. 连接到MongoDB数据库:
from pymongo import MongoClient

client = MongoClient()
db = client['mydatabase']
  1. 选择要删除文档的集合,并使用delete_many()方法删除符合条件的文档:
collection = db['mycollection']
result = collection.delete_many({'name': 'pidancode.com'})
print(result.deleted_count, " documents deleted.")
  1. 选择要插入文档的集合,并使用insert_one()方法将文档插入到集合中:
new_collection = db['newcollection']
new_document = {'name': 'pidancode.com', 'job': 'Python developer'}
result = new_collection.insert_one(new_document)
print(result.inserted_id)

完整代码演示:

from pymongo import MongoClient

client = MongoClient()
db = client['mydatabase']

# delete documents from collection
collection = db['mycollection']
result = collection.delete_many({'name': 'pidancode.com'})
print(result.deleted_count, " documents deleted.")

# insert documents into new collection
new_collection = db['newcollection']
new_document = {'name': 'pidancode.com', 'job': 'Python developer'}
result = new_collection.insert_one(new_document)
print(result.inserted_id)

相关文章