1

My collection is as follows :

{
  "_id" : "",
  "team" : "avenger",
  "persons" : [
    {
      "name" : "ABC",
      "class" : "10",
      "is_new" :  true
    },
    {
      "name" : "JHK",
      "class" : "12",
      "is_new" :  true
    },
    {
      "name" : "BNH",
      "class" : "10",
      "is_new" :  true
    }
  ]
},
{
  "_id" : "",
  "team" : "adrenaline",
  "persons" : [
    {
      "name" : "HTU",
      "class" : "11",
      "is_new" :  true
    },
    {
      "name" : "NVG",
      "class" : "10",
      "is_new" :  true
    },
    {
      "name" : "SED",
      "class" : "8",
      "is_new" :  true
    }
  ]
}

My Goal is to find for all such documents which contain such nested objects in "persons" where "class" is "10" and update "is_new" field to "false"

I am using mongoose update with "multi" set to true

Query :

{                
  persons: { $elemMatch: { class: "10" } }
}

Options:

{
  multi : true
}

Update :

First one I have tried is :

{
  $set : {
    "persons.$.is_new" : false
  }
}

Second one is :

{
  $set : {
    "persons.$[].is_new" : false
  }
}

The issue is : using $ in update operation updates only first match in the "persons" array for all matched documents.

If I use $[], it updates all the objects of "persons" array in the matched documents.

Workaround can be to use a loop for update operation but i believe that should not be the ideal case.

I see nothing in the docs, though have found people reporting this update operation issue.

Is this can't be done using a single query ?? Is looping through documents my only option ?

1 Answer 1

2

You need to set the filtered positional operator $[<identifier>] identifier

Model.update(
  { "persons": { "$elemMatch": { "class": "10" }}},
  { "$set" : { "persons.$[e].is_new" : false }},
  { "arrayFilters": [{ "e.class": "10" }], "multi" : true }
)
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.