Removing mongodb document by its _id without using ObjectId

52 views Asked by At

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?

1

There are 1 answers

1
aneroid On

You can convert a string to an ObjectID within the find query (or aggregation pipeline) with $toObjectId:

db.collection.find({
  $expr: {
    $eq: ["$_id", { $toObjectId: "65fee1b40839f1f886ee94a9" }]
  }
})

Mongo Playground

So your Python code should be:

document_text_id: str = ...  # like "65fee1b40839f1f886ee94a9"
result = collection.delete_one({
  "$expr": {
    "$eq": ["$_id", { "$toObjectId": document_text_id }]
  }
})