Mongodb 所有文档的复杂更新

Mongodb complex updating of all documents

我有一个看起来像这样的集合:

{ 
    "_id" : ObjectId("..."), 
    "cityName" : "New York", 
    "factories" : [
        {
            "factoryName": "factory1",
            "productAmount": 400,
            "numberOfWorkers": 5,
            "workersProductionPerSecond": 0.1
        },
        {
            "factoryName": "factory2",
            "productAmount": 200,
            "numberOfWorkers": 3,
            "workersProductionPerSecond": 0.2
        }
    ]
},
{ 
    "_id" : ObjectId("..."), 
    "cityName" : "New Jersey", 
    "factories" : [
        {
            "factoryName": "New factory",
            "productAmount": 100,
            "numberOfWorkers": 5,
            "workersProductionPerSecond": 0.25
        },
        {
            "factoryName": "New Factory 2",
            "productAmount": 200,
            "numberOfWorkers": 5,
            "workersProductionPerSecond": 0.4
        }
    ]
}

假设我想要一个服务,可以每秒更新所有工厂的productAmount(假设有数百个城市有数百个工厂)每一个 )。 productAmount 的更新需要像这样的伪代码

productAmount += numberOfWorkers (这个工厂的) * workersProductionPerSecond (这个工厂的);

请问有没有高效率的mongodb查询/好的javascript代码来更新所有城市所有工厂的产品数量?或者也许为了做一个简单的查询,工厂应该在他们自己的集合中,并带有城市的外键? 谢谢:)

我建议使用简单的 $map:

db.collection.update({},
[
  {
    $set: {
      factories: {
        $map: {
          input: "$factories",
          as: "item",
          in: {
            factoryName: "$$item.factoryName",
             productAmount: {$add: [{
              $multiply: [
                "$$item.numberOfWorkers",
                "$$item.workersProductionPerSecond"
              ]
            }, "$$item.productAmount"]},
            numberOfWorkers: "$$item.numberOfWorkers",
            workersProductionPerSecond: "$$item.workersProductionPerSecond"
          }
        }
      }
    }
  }
],
{
  multi: true
})

Playground example

不过,如果每个工厂都是一个城市外键的文档,等价查询就更简单了。