0

student collection look like below.

[{
    "_id" : NumberLong(1),
    "studentId" : "70133",
    "subjects" : [ 
        "Mathematics", 
        "Biology and Zoology"
    ]
},
{
    "_id" : NumberLong(2),
    "studentId" : "70134",
    "subjects" : [ 
        "Mathematics", 
        "English"
    ]
},
{
    "_id" : NumberLong(3),
    "studentId" : "70135",
    "subjects" : [ 
        "English", 
        "Mathematics",
        "Chemistry"
    ]
}]);

I want to write a query which will update the student collection subject array values like this:

  • If subject matches English have to be updated to ENG
  • If subject matches Biology and Zoology have to be updated to BAZ
  • If subject matches Mathematics have to be updated to MAT
  • If subject matches Chemistry have to be updated to CHM

After update documents should look like below. How Can I achieve this.

[{
    "_id" : NumberLong(1),
    "studentId" : "70133",
    "subjects" : [ 
        "MAT", 
        "BAZ"
    ]
},
{
    "_id" : NumberLong(2),
    "studentId" : "70134",
    "subjects" : [ 
        "MAT", 
        "ENG"
    ]
},
{
    "_id" : NumberLong(3),
    "studentId" : "70135",
    "subjects" : [ 
        "ENG", 
        "MAT",
        "CHM"
    ]
}]);
rickky
  • 3
  • 3
  • The answer depends upon which version of mongo are you using if you are looking for conditional updates then they are only [supported from v4.2](https://stackoverflow.com/a/56551655/2417602). Else you may have to write a script to do the updates. – vikscool Feb 11 '20 at 06:14

1 Answers1

0

This has to be done with multiple updates like:

db.collection.update(
    { "subjects" : { $in : [ "Mathematics" ] } },
    { $set: { "subjects.$" : "MAT" } },
    { multi: true }
)

See this page for more information regarding updating multiple document

if multi is set to true, the db.collection.update() method updates all documents that meet the criteria. The multi update operation may interleave with other read/write operations.

https://docs.mongodb.com/master/reference/method/db.collection.update/index.html#multi-parameter

Kevin
  • 506
  • 6
  • 13
  • Thank you Kevin, it worked with multiple Update queries." subjects.$ " here $ will get the index of that when condition part of the query? – rickky Feb 11 '20 at 15:28
  • You are welcome! The "subjects.$" is called the positional $ operator and acts as a placeholder for the first element that matches the query document. – Kevin Feb 11 '20 at 15:43