0

I have the following structure in my document:

{
  "_id": ObjectId("5891a85bccaad513a844308f"),
  "sites": [
    {
      "site": "site1",
      "url": "site1.com",
      "status": 1,
    },
    {
      "site": "site2",
      "url": "site2.com",
      "status": 1,
    },
    {
      "site": "site3",
      "url": "site3.com",
      "status": 1,
    }
  ]
}

then I load all sites to UI. then I'll do some changes like following image and hit Update. I have deleted "site3". enter image description here then My structure should update like as follow. site3 status should update to 0

{
  "_id": ObjectId("5891a85bccaad513a844308f"),
  "sites": [
    {
      "site": "site1",
      "url": "site1.com",
      "status": 1,
    },
    {
      "site": "site2",
      "url": "site2.com",
      "status": 1,
    },
    {
      "site": "site3",
      "url": "site3.com",
      "status": 0,
    }
  ]
}

How can I achieve this ?

1 Answer 1

2

You can make use of positional $ update.

The query filter finds the matching site in the array and update part will set the status to 0 to matching element.

collection.updateOne(new Document("_id", new ObjectId("5891a85bccaad513a844308f")).append("sites.site", "site3"), Updates.set("sites.$.status", 0));
Sign up to request clarification or add additional context in comments.

2 Comments

but the problem is How to find what site was deleted from the list. Imagine site2 and site3 will delete, how to get that sites to update ?
I think you should keep track of it in the client code. It would be much simpler that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.