Recalculate field using value from another field in document & calculation

时间:2022-09-13 20:55:08

Doing this in node.js with mongodb-native package.

使用mongodb-native软件包在node.js中执行此操作。

Lets say documents have this structure:

让我们说文档有这样的结构:

{
  name: "Document A", // just a string field
  var1: 10, // some variable, it is increaded if user do a cetrain action
  date_created: '2014-01-07' // stored as ISO date, here I simplified it,
}

For each document in collection I must create-if-not-exist or update varComp variable, and its value should be calculated using values from current document. The calculation formula is something like this (pseudocode):

对于集合中的每个文档,我必须创建 - 如果不存在或更新varComp变量,并且应使用当前文档中的值计算其值。计算公式是这样的(伪代码):

varComp = (5 + var1) / (Date.now() - date_created)^2.5

Updating, as far as I know, in this case must be performed with aggregation framework (due to division), but how do I calculate the power 2.5 of 2 dates difference, which must be expressed in hours before raising? I cannot calculate it on insert/update of var1 only, because regardless every document must be recalculated each, lets say, 5 hours by calling an Recalculate routine.

据我所知,在这种情况下,更新必须使用聚合框架(由于除法),但我如何计算2个日期差异的权力2.5,必须以提升前的小时数表示?我无法仅在插入/更新var1时计算它,因为无论每个文档都必须重新计算,比如说,通过调用Recalculate例程5小时。

1 个解决方案

#1


1  

1.It is not possible to update data in database using aggregation framework. But using aggregation framework you could do some calculations on fly. Unfortunately pow operation is not implemented in Aggregation Framework. You should use MapReduce instead.

1.使用聚合框架无法更新数据库中的数据。但是使用聚合框架,您可以在飞行中进行一些计算。不幸的是,聚合框架中没有实现pow操作。您应该使用MapReduce。

2.Alternatively you could have some separate process that would do calculations by schedule(every 5 hours) and write results in database. Implementation for MongoDb shell:

2.或者你可以有一些单独的过程,按计划进行计算(每5小时一次)并将结果写入数据库。 MongoDb shell的实现:

var myCursor =  db.yourCollection.find({ });

myCursor.forEach(function(d){ 

  var varComp = (5 + d.var1) / Math.pow(Date.now() - d.date_created, 2.5);

  db.yourCollection.update({_id:d._id},{$set:{ varComp: varComp }});

});

#1


1  

1.It is not possible to update data in database using aggregation framework. But using aggregation framework you could do some calculations on fly. Unfortunately pow operation is not implemented in Aggregation Framework. You should use MapReduce instead.

1.使用聚合框架无法更新数据库中的数据。但是使用聚合框架,您可以在飞行中进行一些计算。不幸的是,聚合框架中没有实现pow操作。您应该使用MapReduce。

2.Alternatively you could have some separate process that would do calculations by schedule(every 5 hours) and write results in database. Implementation for MongoDb shell:

2.或者你可以有一些单独的过程,按计划进行计算(每5小时一次)并将结果写入数据库。 MongoDb shell的实现:

var myCursor =  db.yourCollection.find({ });

myCursor.forEach(function(d){ 

  var varComp = (5 + d.var1) / Math.pow(Date.now() - d.date_created, 2.5);

  db.yourCollection.update({_id:d._id},{$set:{ varComp: varComp }});

});