Home > database >  Mongodb complex updating of all documents
Mongodb complex updating of all documents

Time:05-27

I have a collection that looks like this:

{ 
    "_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
        }
    ]
}

And lets say I want to have a service that updates every second the productAmount of all the factories ( imagine there are hundreds of cities with hundreds of factories in each one ). The updating of the productAmount needs to be like this pseudo code

productAmount = numberOfWorkers ( of this factory ) * workersProductionPerSecond (of this factory);

May anyone please suggest a good efficient mongodb query / a good javascript code to update the product amount of all the factories of all the cities? Or maybe in order to make a simple query that does it the factories should be in their own collection with a foreign key for the cities? Thanks :)

CodePudding user response:

I suggest using a simple $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

Nevertheless, if each factory is a document with a foreign key for the city, the equivalent query will be even simpler.

  • Related