Delete all documents returned in a find().limit()

Viewed 142

I'm using db.collection.find({}, {'_id': False}).limit(2000) to get the documents from a collection. This documents are sent to a Facebook API, after the API return success this documents need to be deleted from the collection.

My main doubt is:

  • Is there a way to I delete all this 2000 documents withou using a for loop? I know that collection.find returns a cursor, is there a way to use this cursor in a delete_many?

The structure of my document is:

{
    "_id" : ObjectId("61608068887f1a0e2162d94b"),
    "event_time" : "1632582893",
    "value" : "549.9000",
    "contents" : [ 
        {
            "product_id" : "1-1",
            "quantity" : "1.000000",
            "value" : "10"
        }
    ]
}
1 Answers

To solve this problem, based on the comments of @adarsh and @J.F I've used the following code:

rm = [x['_id'] for x in MongoDB(mongo).db.get_collection("DataToSend").find({}, {'_id' : 1}).limit(2000)

MongoDB(mongo).db.get_collection("DataToSend").delete_many({'_id' : { '$in' : list(rm)}})
Related