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?
Field _id
has type ObjectId
, and "57a49c6c33b10927ff09623e"
has type String.
Instead try
collection.deleteOne(new Document("_id", new ObjectId("57a49c6c33b10927ff09623e")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With