Home > Blockchain >  MongoDB: Can't update in nested arrays
MongoDB: Can't update in nested arrays

Time:08-12

I've been trying to modify a value in multiple arrays for a few arrays and I can't find documentation on how to do this.

My collection looks like this

"rates": [
    {
      "category": "Web",
      "seniorityRates": [
        {
          "seniority": "junior",
          "rate": 100
        },
        {
          "seniority": "intermediate",
          "rate": 135
        },
        {
          "seniority": "senior",
          "rate": 165
        }
      ]
    }
  ]

I'm just trying to modify "junior" to "beginner", this should be simple.

Thanks to these answers:

How can I update a multi level nested array in MongoDB?

MongoDB updating fields in nested array

I've manage to write that python code (pymongo), but it doesn't works...

result = my_coll.update_many({},
        {
            "$set":
            {
                "rates.$[].seniorityRates.$[j].seniority" : new
            }
        },
        upsert=False,
        array_filters= [
                {
                "j.seniority": old
                }
            ]
        )

The path 'rates' must exist in the document in order to apply array updates.

It correspond to this command that doesn't work either

db.projects.updateMany({},
  {
      $set:
      {
          "rates.$[].seniorityRates.$[j].seniority" : "debutant"
      }
  },
  { arrayFilters = [
          {
          "j.seniority": "junior"
          }
      ]
  }
)

clone(t={}){const r=t.loc||{};return e({loc:new Position("line"in r?r.line:this.loc.line,"column"in r?r.column:......)} could not be cloned

What am I doing wrong ?

Any help would be very appreciated

CodePudding user response:

The other option could be Sample

db.collection.update({},
{
  $set: {
    "rates.$[].seniorityRates.$[j].seniority": "debutant"
  }
},
{
  arrayFilters: [
    {
      "j.rate": { //As per your data, you can apply the condition o rate field to modify the level
        $lte: 100
      }
    }
  ]
})

Or

The actual query should work Sample

db.collection.update({},
{
  $set: {
    "rates.$[].seniorityRates.$[j].seniority": "debutant"
  }
},
{
  arrayFilters: [
    {
      "j.seniority": "junior"
    }
  ]
})

The same should work in python, a sample question

CodePudding user response:

So I was just dumb here, I inverted two parameters so I didn't have the correct collection in the python code...

Thanks Gibbs for pointing out where the mistake was in the mongo command.

I will not delete this post as it can help other to know how to do this kind of queries.

  • Related