通过数组对象 属性 更新 mongodb 字段

update mongodb field by an array object property

我正在尝试使用我的节点 js 应用程序 MongoDB 执行一个简单的更新查询操作,该应用程序每晚都会 运行 使用 node-cron 但我无法获得更新运行工作

. 我数据库中的文件看起来像

[
  {
    Balance: 4000,
    name: "Steph curry",
    password: "*****",
    created_At: ISODate("2022-04-19T07:17:29.243Z"),
    deposits: [
      {
        amount: 1000,
        paid: false,
        expiry: 28903708478, // this should be a timestamp
        credit: 150
      },
      {
        amount: 1000,
        paid: false,
        credit: 100,
        expiry: 28903708478 // this should be a timestamp
      }
    ]
  }
]

我想查询存款已过期的所有用户(即 Date.now() > expiry ) 并且他们的支付值是假的,然后将信用添加到他们的余额值,然后将支付值变为真。

/ 基本上我想要的是这样的

db.collection.update({
  "deposits.paid": false,
  "deposits.expiry": { $lt: "$$NOW" }
},
{
  ballance: {
    $add: [ "deposits.$.credit", "$balance" ]
  },
  "deposits.$.paid": true
})

我认为你的到期时间不是有效的时间戳(28903708478=2885/12/2 Sunday 15:54:38),所以你自己转换一下。

$map

$add

$cond

$mergeObjects

db.collection.update({
  "deposits.paid": false,
  "deposits.expiry": { $lt: 28903708479 }
},
[
  {
    $set: {
      Balance: {
        $add: [
          "$Balance",
          {
            $sum: {
              $map: {
                input: "$deposits",
                as: "d",
                in: {
                  $cond: {
                    if: {
                      $and: [
                        { $not: "$$d.paid" },
                        { $lt: [ "$d.expiry", 28903708479 ] }
                      ]
                    },
                    then: "$$d.credit",
                    else: 0
                  }
                }
              }
            }
          }
        ]
      }
    }
  },
  {
    $set: {
      deposits: {
        $map: {
          input: "$deposits",
          as: "d",
          in: {
            $mergeObjects: [
              "$$d",
              {
                paid: {
                  $cond: {
                    if: {
                      $and: [
                        { $not: "$$d.paid" },
                        { $lt: [ "$d.expiry", 28903708479 ] }
                      ]
                    },
                    then: true,
                    else: false
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
],
{
  multi: true
})

mongoplayground