6

I'm trying to remove an element from an array using Java and haven't been successful...

I have a "emailsInApp" collection and inside I have this:

{ "_id" : "750afe", "list" : [ "[email protected]", "[email protected]" ] }
{ "_id" : "711850", "list" : [ "[email protected]" ] }

It holds for each id the registered emails.

What I would like to do is: given an id and an email, remove that email from that appId.

This is what I have atm and when I run it it doesn't change the array at all:

DBCollection emailsApp = db.getCollection(EmailsInAppColl);
BasicDBObject queryEmail = new BasicDBObject();
queryEmail.put("_id", appId);
BasicDBObject updateEmailCommand = new BasicDBObject();
updateEmailCommand.put("$pull", new BasicDBObject("list", email));
emailsApp.update(queryEmail, updateEmailCommand, true, true);

Could you point me in the right direction please?

Edit: As reccomended by @Constantine if I debug it this is what I get:

DBCollection emailsApp = db.getCollection(EmailsInAppColl);
queryEmail.put("_id", appId);
DBCursor cursor = emailsApp.find(queryEmail);
System.out.println("######*****"+cursor.next());

In the console:

#####*****{ "_id" : "711850" , "list" : [ "[email protected]" , "[email protected]" , "[email protected]" , "[email protected]"]}

The search query is correct but it does not remove the item...

2
  • Make sure you have the right collection name in the DBCollection parameter and check if the appId really exists. Please, debug it this way and tell if it is all correct. Commented Jun 12, 2013 at 9:21
  • Hi @Constantine, Thank you for the reply. I did test it using a cursor and it found the id. So it is finding the app, the issue is removing the item... Commented Jun 12, 2013 at 10:31

1 Answer 1

7

Try something, like this:

BasicDBObject match = new BasicDBObject("_id", appId); //to match your direct app document
BasicDBObject update = new BasicDBObject("list", email);
coll.update(match, new BasicDBObject("$pull", update));

It should work.

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

1 Comment

Thank you very much for the help @Constantine. It happens I was thinking in the wrong way, I changed my array to have an id related to each email. From there it is easier for me to maintain the array and solved the issue. You help me find the right way :)

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.