1

Is it possible to update a field using the value of another field?

Here is my schema

var timeSchema = new mongoose.Schema({
    hours: Number,
    minutes: Number
});

module.exports = mongoose.model("Time", timeSchema);

I want the value of minutes to be hours * 60 when minutes become 0

Here is my code

Time.updateMany({}, {minutes: hours * 60});

My code throws an error which says hours is not defined

Is there any possible way to update minutes using the value of hours?

6
  • 2
    Does this answer your question? Update MongoDB field using value of another field Commented May 11, 2020 at 4:08
  • It does not work Commented May 11, 2020 at 4:17
  • @JeromeBravo : What didn't work ? What have you tried & your DB version ? what do you mean by when minutes become 0 ? Commented May 11, 2020 at 4:20
  • Code: Time.updateMany({}, {$set: {minutes: $hours * 60}}); It still says that $hours is not defined. My MongoDB version is 4.2.5 Commented May 11, 2020 at 4:25
  • @whoami I have a function that decrease the number of minutes Commented May 11, 2020 at 4:33

1 Answer 1

2

Starting from MongoDB version 4.2, You can execute aggregation pipeline in updates i.e; you can utilize certain aggregation stages/operators in updates. So update part will be wrapped in [].

Try below query :

Time.updateMany({}, [{$set: {minutes: {$multiply : ['$hours', 60 ]}}}])

In the above query we've used $set alias $addFields stage of aggregation & $multiply aggregation operator to multiple existing hours field with 60 & store the value in minutes field.

Note : Just in case .updateMany() throws any error try the same with .update() with { multi : true } option.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.