0

Partial update removes all other fields in mongodb In DB:

{
  "demo": [
    {
      "id": "ABC123",
      "order": [
        {
          "order": 2,
          "field": "fieldValue"
        }
      ],
      "items": [
        "Story"
      ],
      "statusList": [
        "In progress"
      ]
    }
  ]
}

In java Code:

collection.updateOne(Filters.eq("id", "ABC123"), new Document("$set", doc));

// doc is the document created from Model class

I doc i am passing values for only order. After running Java code it is updating items and statusList as null because of my Model class What should i do? Thanks in advance

Avinash Thakur
  • 81
  • 1
  • 1
  • 10

1 Answers1

0

If you want to update only order, you can do

collection.updateOne(
  Filters.eq("id", "ABC123"), 
  new Document("$set", new Document("order", doc.order))
);

Including only the fields you want to update is what makes this a partial update.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Hi @Thilo,User can update any attributes inside demo so I cannot set it for one specific field. user can update items or statusList also – Avinash Thakur Sep 15 '19 at 10:33
  • You can add as many fields as you want. But you must not add fields you do not want to update. And only your application knows what those are. So you have to keep track of that somewhere. You cannot just pass in the complete model class (as that will contain all fields, regardless of needing an update or not) – Thilo Sep 15 '19 at 10:35
  • If "no change" just means `doc.xxx == null` you can make some simple filtering logic based on that. – Thilo Sep 15 '19 at 10:36
  • Thank you @Thilo,I had one more question consider a scenario: if there are many attributes in request payload and he can change all attributes except one then he will have to mention all the other attributes in update statement – Avinash Thakur Sep 15 '19 at 10:56
  • If you want to update a field, you have to "mention" it in the update call, yes. How else would the database know what to update? – Thilo Sep 15 '19 at 13:53