问题
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" : [ "John@gmail.com", "Mike@gmail.com" ] }
{ "_id" : "711850", "list" : [ "example@gmail.com" ] }
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" : [ "example@gmail.com" , "peanut@gmail.com" , "chewie@gmail.com" , "gold@gmail.com"]}
The search query is correct but it does not remove the item...
回答1:
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.
来源:https://stackoverflow.com/questions/17061665/mongodb-remove-item-from-array