Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove document from array in MongoDB Java

I got a JSON string that looks something like this:

String tmp = "[
   {
      "ID":"12",
      "Date":"2018-02-02",
      "ObjData":[
         {
            "Name":"AAA",
            "Order":"12345",
            "Extra1":{
               "Temp":"3"
            },
            "Extra2":{
               "Temp":"5"
            }
         },
         {
            "Name":"BBB",
            "Order":"54321",
            "Extra1":{
               "Temp":"3"
            },
            "Extra2":{
               "Temp":"5"
            }
         }
      ]
   }
]"

I would like to remove for example the the document where ´Order´ equals "54321" from ´ObjData´. I got the following code:

Document doc = new Document();
doc = Document.parse(tmp);

Document fields = new Document("ID", "12")
    .append("ObjData", Arrays.asList(new Document("Order", "54321")));

Document update = new Document("$pull", fields);

coll.updateOne(doc, update);

I am trying to use the ´pull´ method to remove the entire document from the array where the ´Order´ equals 54321 but for some reason it's not working, I am probably doing something wrong. Could someone point out the issue please?

Also, what would be the best way to keep count of the documents within the array so that once all documents are pulled the entire document is deleted from the database? Would it be good to add some kind of ´size´ attribute and keep track of the size and decrease it after each pull?

like image 457
Erik L Avatar asked Sep 20 '26 15:09

Erik L


1 Answers

To remove document with Order=54321 from internal array from any document (if you don't know ID) you can use empty filter like:

    Document filter = new Document();
    Document update = new Document("$pull", new Document("ObjData", new Document("Order", "54321")));

    coll.updateOne(filter, update);
like image 156
Yuriy Alevohin Avatar answered Sep 22 '26 04:09

Yuriy Alevohin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!