0

I want to update the Status field inside array list of Slots where id = "".

Sample data

{
  "_id": ObjectId("621e816e7a938400016c5c64"),
  "Resource": "[email protected]",
  "School": {
    "Class": [
      {
        "Type": "ABC",
        "Slots": [
          {
            "id": "",
            "Duration": "1 week",
            "Status": "Released",
            "Selected": true
          },
          {
            "id": "123",
            "Duration": "1 week",
            "Status": "Released",
            "Selected": true
          }
        ]
      }
    ]
  }
}

This is how I am approaching:

db.getCollection("XYZ").update({
  "Resource": "[email protected]",
  "School.Class": {
    "$elemMatch": {
      "Type": "ABC",
      "Slots.Status": "Released",
      "Slots.id": "",
      "Slots.Duration": "1 week"
    }
  }
},
{
  $set: {
    "School.Class.$[outer].Slots.$[inner].Status": "Confirmed"
  }
},
{
  "arrayFilters": [
    {
      "outer.Type": "ABC"
    },
    {
      "inner.Duration": "1 week"
    }
  ]
})

But it is updating the status as confirmed for the both the array list.How can I update the particular field where "Slots.id" : "" . Please forgive me in case of any misalignment or brackets missing in data

1 Answer 1

1

If I've understood correctly you are almost there, since you want to update only values where id is "" you have to add that condition into arrayFilters: "inner.id": "".

db.collection.update({
  "Resource": "[email protected]",
  "School.Class": {
    "$elemMatch": {
      "Type": "ABC",
      "Slots.Status": "Released",
      "Slots.id": "",
      "Slots.Duration": "1 week"
    }
  }
},
{
  $set: {
    "School.Class.$[outer].Slots.$[inner].Status": "Confirmed"
  }
},
{
  "arrayFilters": [
    {
      "outer.Type": "ABC"
    },
    {
      "inner.Duration": "1 week",
      "inner.id": ""  // <--- This line
    }
  ]
})

Example here

Sign up to request clarification or add additional context in comments.

Comments

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.