【问题标题】:Update MongoDB document with its own fields使用自己的字段更新 MongoDB 文档
【发布时间】:2022-04-13 03:35:45
【问题描述】:

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

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
  • 请问我们可以提供示例数据集和预期输出吗?对于自动更新,您可能需要查看trigger
  • 我添加了更多解释和图像

标签: mongodb mongoose atomic document


【解决方案1】:

也许像这样

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多