Sai Darshan
Sai Darshan

Reputation: 387

Update with same document field in mongodb

I have a this document.Which has a schema of below:

 rental:{
    total:Number,
    due:Number
}

For example let us assume the document is filled with values like this:

 rental:{
    total:350,
    due:10
}

I want to replace the value of 'total' to 'due'.So i want it to be like this:

 rental:{
    total:350,
    due:350
}

I came accross $set,i did something like this: PS:"User" is the name of the model.(which i havent refrenced here)

User.updateMany({},{$set:{'due':"$total"}},function(err,..}{ 
//do whatever
    }

But this didnt work out.I ran into a CastError. I also came accross '$replaceWith'.But i didnt understand a bit on how to use that in my case.Any help is appriciated.Thank you

Upvotes: 2

Views: 36

Answers (1)

Ashh
Ashh

Reputation: 46491

You can use below query

db.collection.update(
  { },
  [{ "$set": { "due": "$total" }}]
)

Upvotes: 1

Related Questions