1

I am trying to update an array as specified on this MongoDB official tutorial link. The Steps that I have followed is:

  1. Create collection name test:

  2. Insert document in collection:

    db.getCollection('test').insert({"_id" : 2,"grades" : [{ "grade" : 90, "mean" : 75, "std" : 6 },{ "grade" : 87, "mean" : 90, "std" : 3 },{ "grade" : 85, "mean" : 85, "std" : 4 }]});

    db.getCollection('test').insert({"_id" : 1,"grades" : [{ "grade" : 80, "mean" : 75, "std" : 6 },{ "grade" : 85, "mean" : 90, "std" : 4 },{ "grade" : 85, "mean" : 85, "std" : 6 }]});

  3. Trying to update an array as specified in a tutorial:

    db.getCollection('test').update( { }, { $inc: { "grades.$[].std" : -2 } }, { multi: true } )

As per tutorial, it must update the document. But, instead I receives an error:

cannot use the part (grades of grades.$[].std) to traverse the element ({grades: [ { grade: 80.0, mean: 75.0, std: 6.0 }, { grade: 85.0, mean: 90.0, std: 4.0 }, { grade: 85.0, mean: 85.0, std: 6.0 } ]})

I am using MongoDB 3.4 Does anyone know the solution?

Anand Vaidya
  • 609
  • 2
  • 16
  • 41
  • What Mongo version are you running? The `$[]` operator has been introduced in 3.6 – Boaz Apr 26 '18 at 09:19
  • 1
    It is version 3.4 – Anand Vaidya Apr 26 '18 at 09:20
  • Well, there you have it? :) – Boaz Apr 26 '18 at 09:20
  • @Boaz Thank you. I will update mongoDB – Anand Vaidya Apr 26 '18 at 09:24
  • As noted, this is not supported in anything below MongoDB 3.6. Even if you do upgrade, I'm guessing by your usage of `getCollection()` you're probably using Robo 3T. If so beware that the product is still based on the core build of the mongo shell from 3.4. This means that various options such as `arrayFilters` get removed from update statements before they are sent to the server. See the notes on the canonical question for more information – Neil Lunn Apr 26 '18 at 09:56
  • @NeilLunn You are absolutely right. After updating mongo to 3.6 I am not able to fire these queries in Robo 3T. – Anand Vaidya Apr 26 '18 at 10:05
  • https://stackoverflow.com/questions/51777183/cannot-use-the-part-to-traverse-the-element/51807509#51807509 – Ashh Aug 26 '18 at 08:35

1 Answers1

0

Use $[] positional operator to update the nested array elements... It will modify all elements in the specified array field.

db.collection.update({}, { "$inc": { "grades.$[].std": -2 } })
Ashh
  • 44,693
  • 14
  • 105
  • 132