0

In my mongodb I have around 20K records, now From the same mongodb I am importing only 500 records in python and now I need to delete those 500 records which I have imported , is it possible to delete those 500 records using python?

my code for importing 500 records

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

1 Answer 1

2

You would need to use the _id for each record so that you could tell pymongo which records to delete. For example:

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}
    },
)
Sign up to request clarification or add additional context in comments.

3 Comments

hi @forgetso I am getting error for the above code TypeError: 'Collection' object is not callable. If you meant to call the 'deleteMany' method on a 'Collection' object it is failing because no such method exists.
My bad, it should be delete_many for pymongo (deleteMany in Mongo shell). I've updated the answer. Let me know if this works for you.
Glad to hear it :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.