Mongodb removes an element from an array

I am trying to remove an element from an array using Java and was not successful ...

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

{ "_id" : "750afe", "list" : [ " John@gmail.com ", " Mike@gmail.com " ] } { "_id" : "711850", "list" : [ " example@gmail.com " ] } 

It contains registered emails for each identifier.

What I would like to do is to specify the identifier and email address, delete this email from this application.

This is what I have atm, and when I run it, it does not 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?

Edit: As recommended 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 delete the item ...

+6
source share
1 answer

Try something like:

 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.

+7
source

Source: https://habr.com/ru/post/947093/


All Articles