1

I have MongoDB entries which looks like this:

{
"_id" : ObjectId("57288862e4b05f37bc6ab91b"),
"_class" : "mydomain.ScheduleAbsenceContainer",
"containerStart" : ISODate("2016-04-06T07:30:00Z"),
"containerEnd" : ISODate("2016-04-06T10:00:00Z"),   
"scheduleIntervalContainerAbsenceType" : "SCHOOL",
"scheduleIntervalContainers" : [
    {
        "_id" : null,
        "marker" : 6,           
        "containerType" : "SCHOOL",         
    }
  ] 
}

and I will change all scheduleIntervalContainerAbsenceType from SCHOOL to SPARE_TIME and also all containerType's from SCHOOL to SPARE_TIME. Is there a simple possibility to do this?

quma
  • 5,233
  • 26
  • 80
  • 146
  • Possible duplicate of [MongoDB - Update an object in nested Array](http://stackoverflow.com/questions/34431435/mongodb-update-an-object-in-nested-array) – felix Mar 27 '17 at 07:21

1 Answers1

0

Below code does what you want. It updates all the documents which has the "SCHOOL" value for "scheduleIntervalContainerAbsenceType" keys.

db.collection_name.find({"scheduleIntervalContainerAbsenceType" : "SCHOOL"})
  .forEach(function (doc) {
    doc.scheduleIntervalContainers.forEach(function (sch) {
      if (sch.containerType === "SCHOOL") {
        sch.containerType="SPARE_TIME";
      }
    });
    doc.scheduleIntervalContainerAbsenceType="SPARE_TIME";
    db.collection_name.save(doc);
  });

If you want to update all the documents without checking "scheduleIntervalContainerAbsenceType" value (still updating it to "SPARE_TIME") change your query like that.

db.collection_name.find({})
  .forEach(function (doc) {
    doc.scheduleIntervalContainers.forEach(function (sch) {
      if (sch.containerType === "SCHOOL") {
        sch.containerType="SPARE_TIME";
      }
    });
doc.scheduleIntervalContainerAbsenceType="SPARE_TIME";
    db.collection_name.save(doc);
  });