是的,这是可能的!如果要取消设置集合中多个文档的 已知 字段以外的所有字段,最好的方法是使用“批量”操作。
MongoDB 3.2 弃用了 Bulk() 及其相关方法。所以如果你应该使用.bulk_write()。
from itertools import zip_longest # or izip_longest in Python 2.x
from pymongo import MongoClient, UpdateOne
client = MongoClient()
db = client.db
collection = db.collection
requests = []
fields = ['name', '_id']
for document in collection.find():
unset_op = dict(zip_longest(set(document.keys()).difference(fields), [''], fill_value=''))
requests.append(UpdateOne({'_id': document['_id']}, {'$unset': unset_op}))
# Execute per 1000 operations and re-init.
if len(requests) == 1000:
collection.bulk_write(requests)
requests = []
# clean up the queues
if requests:
collection.bulk_write(requests)
对于单个文档,您需要使用 find_one 方法返回与您的条件匹配的文档,然后使用 3.0 版中的 replace_one 新方法
document = collection.find_one({'_id': 111})
collection.replace_one({'_id': document['_id']}, dict(zip(fields, [document[field] for field in fields])))
如果您使用的不是最新版本的 MongoDB 或 Pymongo 驱动程序,则需要使用Bulk() API。
bulk = collection.initialize_unordered_bulk_op()
count = 0
for document in collection.find():
unset_op = dict(zip_longest(set(document.keys()).difference(fields), [''], fill_value=''))
bulk.find({'_id': document['_id']}).update_one({'$unset': unset_op})
count = count + 1
if count % 1000 == 0:
bulk.execute()
bulk = collection.initialize_unordered_bulk_op()
if count > 0:
bulk.execute()
对于单个文档,您可以依赖 update_one 方法。
unset_op = dict(izip_longest(set(document.keys()).difference(fields), [''], fill_value=''))
collection.update_one({'_id': document['_id']}, {'$unset': unset_op})