问题
Can MongoDB allow updating a number field using another number field in same document ? Let say I have a document like below :
{
"_id" : "1",
"a" : 2,
"b" : 3
}
a and b fields are number fields(decimal,int...) my goal is update field b using field a How can I set b like b = 2*a. Is this possible ?
回答1:
Note :
- On v
3.6
you don't have an option for direct update, You need to first read & process in code, then update. - For v
>= 4.2
you can do it in one call as .update() will accept aggregation pipeline & things can be done in one update call to DB. You can try this :
Query :
db.getCollection('collectionName').update({}, [{ $set: { b: { $multiply: ["$a", 2] } } }])
来源:https://stackoverflow.com/questions/60418883/how-to-update-a-number-field-using-another-number-field-in-mongodb