0

I want to find any document in my collection that:

  • its hobby field is empty
  • or its hobby field doesn't exist

and then set the value of its hobby field to be equivalent of its sports field.

 db.myCollection.update(
            { $or: [{"hobby": {$exists: false} },{"hobby": ""}]}
        , {
            $set: {
                hobby: ????sports
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  

With this command above, I suppose I will be passing the value of sports as fixed value to all matching documents. is there any way to pick up its corresponding sports value and set it to hobby?

Bonnard
  • 389
  • 2
  • 8
  • 26
  • 1
    Possible duplicate of [Update MongoDB field using value of another field](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) – Robert Dec 17 '17 at 13:20

2 Answers2

0

You have to do this in 2 queries:

db.myCollection.find({ 
  $or: [{ "hobby": { $exists: false } }, { "hobby": "" }]
}).toArray().forEach(function (item) {
    db.myCollection.update(
      { _id: item._id },
      { $set: { hobby: item.sports } },
      { multi: true }
    )
  })
})
Kerumen
  • 4,193
  • 2
  • 19
  • 33
0

here is the modified version that updates correctly the values:

   db.myCollection.find({ 
      $or: [{ "hobby": { $exists: false } }, { "hobby": "" }]
    }).toArray().forEach(function (item) {
        db.myCollection.update(
          { _id: item._id },
          { $set: { hobby: item.sports } },
          { multi: true }
        )
      })
    })
Marcel
  • 2,764
  • 1
  • 24
  • 40