简体   繁体   中英

Removing object from collection, using the Java mongo driver

This is my sample code:

DBCollection coll = db.getCollection("testCollection");

BasicDBObject search = new BasicDBObject("$search", "mytextsearch");
BasicDBObject textSearch = new BasicDBObject("$text", search);

BasicDBObject projection = new BasicDBObject("score", new BasicDBObject("$meta",   "textScore"));
myDoc = coll.findOne(textSearch, projection);

This should find the document, I call it myDoc, with the highest score for searching "mytextsearch".

Then, I want to remove this document from the collection, so I did:

coll.remove(myDoc);

However, this has no effect on the collection, and myDoc is never deleted. What am I doing wrong? I want to be able to delete myDoc after I have found it.

The remove-method does not remove the document you pass to it. It removes all documents which have all fields in common with the DBObject passed. Why is this distinction important in this case? Because you are using a projection to change the document.

After the projection, the DBObject has a new field textScore=something . When you then pass that DBObject to .remove() , the database will only delete a document which also has a field textScore with that exact value. Because the original document in the collection hasn't got this field, it doesn't get deleted.

So what do you do instead?

Create a new BasicDBObject with only the _id of the document you want to delete and nothing else. Because the _id field is always unique and automatically indexed, this will be both unambiguous and fast. Then pass this one to .remove .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM