I have a simple operation to remove a document from MongoDB using MongoTemplate. The reason for using MongoTemplate is because the project is not directly associated with the service utilizing the database, hence it does not require, and should not require, the database model classes itself.
The query is as follows:
Criteria criteria = Criteria.where("_id")
.is(new ObjectId(id));
mongoTemplate.remove(Query.query(criteria), collectionName);
Where id
is a String object, and collectionName
is the name of the collection.
However, the query, when translated to MongoDB syntax by Spring Data MongoDB, produces such expression:
{ "_id" : { "$oid" : "5e206994943f3c1d6c778efb"}}
instead of { "_id" : ObjectId("5e206994943f3c1d6c778efb")}
.
As a result, the data persists in the database, even though it should be removed. When I try the former query on Mongo shell itself, it throws the error of Unknown operator: $oid
.
Is there anything wrong that I did? How to fix them?
Thank you.
I finally was able to fix this by using MongoDatabase instead. By using the method deleteOne
I was able to delete by _id
with creating new ObjectId(id)
, wrapped under BasicDBObject
.