Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb remove item from array

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...

like image 307
HeWhoBuilds Avatar asked Jun 12 '13 09:06

HeWhoBuilds


1 Answers

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.

like image 74
user Avatar answered Oct 22 '22 12:10

user