arrays - 如何根据另一个字段更新 mongodb 中的数组 dict 元素
问题描述
如何根据将函数应用于另一个字段(位于不同的嵌入文档中)来更新文档中的值?
使用下面的示例数据,我想
- 为有12 个农场的
col
田地id
- 乘以 0.025
statistic.crypt
添加字段的当前值- 通过将其转换为确保值是双精度
$toDouble
- 将结果存储回
statistic.crypt
数据:
{
"_id": {
"$oid": "6128c238c144326c57444227"
},
"statistic": {
"balance": 112570,
"diamond": 14,
"exp": 862.5,
"lvl": 76,
"mn_exp": 2.5,
"lvl_mn_exp": 15,
"coll_ms": 8047,
"all_exp": 67057.8,
"rating": 0,
"crypt": 0
},
"inventory": {
"farm": [{
"id": 12,
"col": 100,
"currency": "diamond",
"cost": 2,
"date": "2021-09-02 18:58:39"
}, {
"id": 14,
"col": 1,
"currency": "diamond",
"cost": 2,
"date": "2021-09-02 16:57:08"
}],
"items": []
},
...
}
我最初的尝试是:
self.collection
.update_many({"inventory.farm.id": 12}, [{
"$set": {
"test": {
'$toDouble': {
"$sum": [
{'$multiply':["$inventory.farm.$[].col", 0.025]},
'$test'
]
}
} }
},])
这不起作用,因为它适用于test
而不是statistic.crypt
,我无法弄清楚如何修改它以适用于statistic.crypt
.
解决方案
一个字段可以在以下阶段基于另一个字段进行更新:
- 添加包含农场的字段
- 设置
statistic.crypt
为数学表达式的结果(应用于新嵌入的场) - 删除额外的字段
在代码中:
self.collection.update_many({"inventory.farm.id": 12 }, [
{
$addFields: {
hh: {
$filter: {
input: "$inventory.farm",
as: "z",
cond: { $eq: ["$$z.id", 12] },
},
},
},
},
{
$set: {
"statistic.crypt": {
$toDouble: {
$sum: [
{
$multiply: [{ $first: "$hh.col" }, 0.025],
},
"statistic.crypt",
],
},
},
},
},
{
$project: {
id_pr: 1,
id_server: 1,
role: 1,
warns: 1,
id_clan: 1,
statistic: 1,
design: 1,
date: 1,
inventory: 1,
voice: 1,
},
},)
推荐阅读
- python - SQLAlchemy:SAWarning:完全 NULL 主键标识无法加载任何对象
- python - 在python中从html获取2个值的最佳方法
- angular - 带有 fieldname 参数的补丁
- python - 某个函数的最大值
- scala - 如何在 Spark Scala 的 Spark 数据框中组合两个 Set
- xml - 列表的标记结构
- data-warehouse - 如何在同一个星型模式中容纳两个依赖事实表?
- r - R 版本 4.0.3+ 64 位拒绝在 Windows 10 上启动
- here-api - 当前位置指示器 HERE SDK 精简版
- python - 带有对象数组的 Python 冒泡排序