Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo : delete records elegantly

Here is my code to delete a bunch of records using pymongo

ids = [] with MongoClient(MONGODB_HOST) as connection:     db = connection[MONGODB_NAME]     collection = db[MONGODN_COLLECTION]     for obj in collection.find({"date": {"$gt": "2012-12-15"}}):         ids.append(obj["_id"])     for id in ids:         print id         collection.remove({"_id":ObjectId(id)}) 

IS there a better way to delete these records? like delete a whole set of records directly

collection.find({"date": {"$gt": "2012-12-15"}}).delete() or remove() 

or delete from obj like

 obj.delete() or obj.remove() 

or somehting similar?

like image 458
icn Avatar asked Dec 19 '12 20:12

icn


People also ask

How do I delete a record in PyMongo?

To delete one document, we use the delete_one() method. The first parameter of the delete_one() method is a query object defining which document to delete. Note: If the query finds more than one document, only the first occurrence is deleted.

Is PyMongo MongoClient thread safe?

Is PyMongo fork-safe? ¶ PyMongo is not fork-safe. Care must be taken when using instances of MongoClient with fork() .

How do I remove all records from a collection in MongoDB?

To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.


1 Answers

You can use the following:

collection.remove({"date": {"$gt": "2012-12-15"}}) 
like image 143
Jorge Puente-Sarrín Avatar answered Sep 24 '22 09:09

Jorge Puente-Sarrín