使用自己的字段更新 MongoDB 个文档

Update MongoDB document with its own fields

我正在尝试为我的 mongodb 文档创建一个 popularityIndex 字段,如下所示:

popularityIndex: {
    type: Number,
    default: function() {
        return this.views.count * 0.3 + this.upVoted.count * 0.3 - this.downVoted.count * 0.1 - ((new Date().getTime() - this.creationDate.getTime())) * 0.2
    },
},

我想知道是否有一种方法可以在它依赖的字段之一更新时更新此字段,同时保持原子性,或者在更新时获取字段,如下所示:

await Model.updateOne({ _id }, { 
       $set: { popularityIndex: 'views.count' * 0.3 + 'upVoted.count' * 0.3 - 'downVoted.count' * 0.1 - ((new Date().getTime() - 'creationDate'.getTime()) / 10000000) * 0.2 }
})

这些是我需要更新的字段,最后一个是被更新的字段:

{ 
  "upVoted": {
       "count": "2"
  },
  "downVoted": {
       "count": "3"
  },
  "views": {
       "count": "5"
  },
  "creationDate": "2022-04-11T16:02:39.956+00:00",
  "popularityIndex": "1.453"
}

因此,如果文档收到赞成票,我也必须更新流行度指数:

await Model.updateOne({ _id }, {
   $inc: { 'upVoted.count': 1 }
}

await Model.updateOne({ _id }, {
   $set: { popularityIndex: this.views.count * 0.3 + this.upVoted.count * 0.3 - this.downVoted.count * 0.2 - ((new Date().getTime() - this.creationDate.getTime())) * 0.2 }
}) // <-- this is the part I don't know

可能是这样

db.collection.updateOne({ _id }, [
  {
    $set: {
      popularityIndex: {
        $sum: [
          { $multiply: [ "$views.count", 0.3 ] },
          { $multiply: [ "$upVoted.count", 0.3 ] },
          { $multiply: [ "$downVoted.count", -0.2 ] },
          { $multiply: [ { $dateDiff: { startDate: "$creationDate", endDate: "$$NOW", unit: "second" } }, -0.2 ] }
        ]
      }
    }
  }
])

Mongo Playground