Search code examples
pythondatabasemongodbmongodb-querypymongo

Delete Document in MongoDB by ObjectId only (pymongo)


If the ObjectId in a MongoDB is unique, then there should be a way to delete the corresponding Document without the need to mention the Collection it belongs to.

Is there a way to delete a Document from a MongoDB in one line, when I don't know the specific Collection it belongs to?

I want to skip looping over the list of Collection names and execute the command db_name.collection_name.delete_one({'_id': ObjId}) that many times.


Solution

  • While in practically Mongo's ObjectId's can be considered unique there is no rule that enforces that, for example I can copy a document from collectionA to collectionB, now both of these documents have an identical ObjectId _id field, additionally some people prefer to generate their own _id values, which again will not necessarily be unique, especially across all collection.

    This is just a theoretical explanation as to why the functionality you seek does not exist, the more practical reason is that no one (hardly no one) actually uses a database like this, if this was an actual need it would have been naturally implemented at some point.

    I personally recommend you revisit the reason that led you to this need, perhaps it makes sense in your case, but perhaps you are violating some core principals and could make your code more reliable by refactoring it.


    TLDR:

    This is not part of Mongo's (and any database as far as I know) functionality, you will have to iterate over all collections.