如何根据另一个字段更新 mongodb 中的数组字典元素
How to Update Array dict Elements in mongodb based on another field
如何根据将函数应用于另一个字段(位于不同的嵌入文档中)来更新文档中的值?
有了下面的示例数据,我想
- 获取具有
id
12 的农场的 col
字段
- 乘以 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,
},
},)
如何根据将函数应用于另一个字段(位于不同的嵌入文档中)来更新文档中的值?
有了下面的示例数据,我想
- 获取具有
id
12 的农场的 - 乘以 0.025
- 添加
statistic.crypt
字段的当前值 - 通过使用
$toDouble
转换来确保该值为双精度值
- 将结果存储回
statistic.crypt
col
字段
数据:
{
"_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,
},
},)