如何使用 MongoDB 中的另一个数字字段更新数字字段 [英] how to update a number field using another number field in MongoDB
本文介绍了如何使用 MongoDB 中的另一个数字字段更新数字字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
MongoDB 可以允许使用同一文档中的另一个数字字段更新数字字段吗?假设我有一个如下所示的文档:
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 和 b 字段是数字字段(十进制,整数...)我的目标是使用字段 a 更新字段 b如何将 b 设置为 b = 2*a.这可能吗?
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 ?
推荐答案
注意:
- 在 v
3.6
上,您没有直接更新的选项,您需要先阅读 &在代码中处理,然后更新. - 对于 v
>= 4.2
,您可以通过 .update() 将接受聚合管道 &可以在一次对 DB 的更新调用中完成操作.你可以试试这个:
- 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 :
查询:
db.getCollection('collectionName').update({}, [{ $set: { b: { $multiply: ["$a", 2] } } }])
这篇关于如何使用 MongoDB 中的另一个数字字段更新数字字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文