<p>是的,有可能!如果要取消设置集合中多个文档的<em>已知</em>字段之外的所有字段,则最好的方法是使用“bulk”操作。在</p>
<p>mongodb3.2不推荐使用<a href="http://api.mongodb.org/python/current/api/pymongo/bulk.html#module-pymongo.bulk" rel="nofollow">^{<cd1>}</a>及其关联方法。所以如果你应该使用<a href="http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write" rel="nofollow">^{<cd2>}</a>。在</p>
<pre><code>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)
</code></pre>
<p>对于单个文档,您需要使用<a href="http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one" rel="nofollow">^{<cd3>}</a>方法,该方法返回与您的条件匹配的文档,然后<a href="http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one" rel="nofollow">^{<cd4>}</a>在3.0版本中新增</p>
^{pr2}$
<hr/>
<p>如果不使用最新版本的MongoDB或Pymongo驱动程序,则需要使用<code>Bulk()</code>API。在</p>
<pre><code>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()
</code></pre>
<p>对于单个文档,您可以依赖<a href="http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one" rel="nofollow">^{<cd6>}</a>方法。在</p>
<pre><code>unset_op = dict(izip_longest(set(document.keys()).difference(fields), [''], fill_value=''))
collection.update_one({'_id': document['_id']}, {'$unset': unset_op})
</code></pre>