我有一个 mongodb 数据库。我目前正在使用 pymongo 编写一个 python 脚本来清理数据。 我的数据集有一个属性“国家/地区”。我正在尝试删除“国家/地区”属性不是美国的所有元组。
我知道如何使用 unset 从数据库中删除属性,并且我知道如何使用删除许多删除属性。
mongo_collection.delete_many({"Country":""})
mongo_collection.update({}, {'$unset': {'Country':1}}, multi=True)
但是,我找不到任何有关如何删除与特定属性值不匹配的所有元组的资源。 任何见解将不胜感激! 谢谢!
最佳答案
只需将您的条件($ne
--> 不等于)传递给delete_many
countries_fixtures = [
{"Country": "FR", "other": "A"},
{"Country": "US", "other": "B"},
{"Country": "AT", "other": "C"},
{"Country": "US", "other": "D"}
]
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.test_stack_088
db.test_stack_088.drop() # Remove whole collection (to make sure test works)
for country_fixture in countries_fixtures:
db.test_stack_088.insert_one(country_fixture)
# We should have 4 records in our test_stack_088 collection, right? RIGHT??
assert db.test_stack_088.count() == 4
# Question's answer:
db.test_stack_088.delete_many({"Country": {"$ne": "US"}}) # <---- This
# Yep, the line above is the juicy part...
# Let's make sure, 100% sure it worked...
assert db.test_stack_088.count() == 2
for record in db.test_stack_088.find():
print(record)
您可以查看 this link 上的比较运算符.
关于python - Pymongo - 删除没有特定属性的数据库元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48028180/