0

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.

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Too bad I do not yet have a 15 reputation, or I would have given you a +1. Thank you for the very clear answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.