I've encountered an issue where I need to remove a MongoDB document by its _id without utilizing ObjectId in the PyMongo library. Typically, it seems that ObjectId needs to be imported and used for identifying documents for removal. However, I'm exploring whether there's an alternative method to achieve this without relying on ObjectId. As an example below is the document that i wish to remove
MongoDB Document
{ _id: ObjectId("65fee1b40839f1f886ee94a9"), category: 'Cars' }
Python code with PyMongo
import pymongo
from bson import ObjectId
document_id = ObjectId("65fee1b40839f1f886ee94a9")
result = collection.delete_one({"_id": document_id})
if result:
return result.deleted_count
In This example i have used ObectId for document removal. Could anyone provide insights or suggestions on how to remove a document by its _id using PyMongo without explicitly using ObjectId?
You can convert a string to an ObjectID within the find query (or aggregation pipeline) with
$toObjectId:Mongo Playground
So your Python code should be: