How to delete document by _id in MongoDB 3.3 using Java
10,929
Field _id
has type ObjectId
, and "57a49c6c33b10927ff09623e"
has type String.
Instead try
collection.deleteOne(new Document("_id", new ObjectId("57a49c6c33b10927ff09623e")));
Author by
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
I'm having a bit of an issue figuring out how to delete a document by _id in MongoDB. I can delete by other attributes no problem but I seem to be missing the correct syntax for deleting by _id.
My document has the following format :
{ "_id" : { "$oid" : "57a49c6c33b10927ff09623e" }, "name" : "Brad" }
And here is the Java code I am using :
// Boiler plate MongoClient client = new MongoClient( "localhost" , 27017 ); MongoDatabase db = client.getDatabase("my-database"); MongoCollection<Document> collection = db.getCollection("my-collection") // This works collection.deleteOne(new Document("name", "Brad")); // This does not work collection.deleteOne(new Document("_id", "57a49c6c33b10927ff09623e"));
Anyone have any idea where I am going wrong?