首页 > 解决方案 > 如何根据另一个字段更新 mongodb 中的数组 dict 元素

问题描述

如何根据将函数应用于另一个字段(位于不同的嵌入文档中)来更新文档中的值?

使用下面的示例数据,我想

  1. 为有12 个农场的col田地id
  2. 乘以 0.025
  3. statistic.crypt添加字段的当前值
  4. 通过将其转换为确保值是双精度$toDouble
  5. 将结果存储回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.

标签: arrayspython-3.xmongodbdictionarypymongo

解决方案


一个字段可以在以下阶段基于另一个字段进行更新:

  1. 添加包含农场的字段
  2. 设置statistic.crypt为数学表达式的结果(应用于新嵌入的场)
  3. 删除额外的字段

在代码中:

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,
    },
  },) 

推荐阅读