如何使用python在mongo db中删除数据

时间:2018-11-14 15:24:09

标签: python mongodb import

在我的mongodb中,我有大约2万条记录, 现在我从同一个mongodb中仅以python导入500条记录,现在我需要删除已导入的那500条记录,是否可以使用python删除那500条记录?

我的导入500条记录的代码

from pymongo import MongoClient
con = MongoClient(local host, 27017)
db = con.rssfeeds_db
data = pd.DataFrame(list(db.restdata.find().limit(500)))

1 个答案:

答案 0 :(得分:1)

您需要为每个记录使用_id,以便您可以告诉pymongo删除哪些记录。例如:

from pymongo import MongoClient
con = MongoClient(localhost, 27017)
db = con.rssfeeds_db

// create a list of the records. each one will be a dict.
records = [x for x in db.restdata.find().limit(500)]

// create a list of the 500 ids so we only need to call the db once
record_ids = [record['_id'] for record in records]

//create your dataframe
data = pd.DataFrame(records)

// delete all 500 records at once
db.restdata.delete_many(
    {'_id': 
        {'$in': record_ids}
    },
)