是的,这是可能的!如果要取消设置集合中多个文档的已知字段以外的所有字段,最好的方法是使用“批量”操作。
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
方法,该方法返回如果您没有使用最新的符合您的条件,然后replace_one
新版本3.0
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})
是的,这是可能的。我还为这个问题添加了一个答案,以显示如何在shell中执行此操作。 – styvane