python - Pymongo - 删除没有特定属性的数据库元组

标签 python mongodb pymongo

我有一个 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/

相关文章:

javascript - 如何在集合中过滤mongoDB中的查询

mongodb - Mongodb Change Streams 未将所有更新返回到集合

mongodb - MongoDB 中数十亿小文档的快速搜索策略

python - 在 Pymongo 中执行批量插入时如何忽略错误。我在 pymongo 中使用有序的批量写入操作

python - 游戏代码中存在缩进问题

python - Try语句语法

node.js - "ERROR while connecting to database. Error: Error: No valid replicaset instance servers found"

python - Lightgbm 排名示例

python - 有没有办法从 PyEnchant 获取随机单词?

python - PyMongo游标batch_size