我有一个mongodb数据库。我目前正在使用pymongo编写一个python脚本来清理数据。 我的数据集有一个属性'country'。我试图删除所有'country'属性不是美国的元组。
我知道如何使用unset从数据库中删除属性,并且我知道如何使用remove many删除属性。
mongo_collection.delete_many({"Country":""})
mongo_collection.update({}, {'$unset': {'Country':1}}, multi=True)
但是,我找不到有关如何删除与特定属性值不匹配的所有元组的任何资源。 任何见解将不胜感激!!! 谢谢!
答案 0 :(得分:1)
将您的条件($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上的比较运算符。