0

I have the following MongoDB document:

{
    "_id" : ObjectId("5f6915c007f67a4588ec5f93"),
    "timestamp" : "2021-06-01T00:00:00Z",
    "sensor_id" : 1,
    "location_id" : 1,
    "measures" : [
        {
            "measure" : "Electricity_consumption",
            "value" : 0.0134,
            "unit" : "kWh/m2"
        },
        {
            "measure" : "Temperature",
            "value" : 24,
            "unit" : "ºC"
        }
    ]
}

What I want to achieve, assuming a kWh price of 0.1€

{
    "_id" : ObjectId("5f6915c007f67a4588ec5f93"),
    "timestamp" : "2021-06-01T00:00:00Z",
    "sensor_id" : 1,
    "location_id" : 1,
    "measures" : [
        {
            "measure" : "Electricity_consumption",
            "value" : 0.0134,
            "unit" : "kWh/m2"
        },
        {
            "measure" : "Temperature",
            "value" : 24,
            "unit" : "ºC"
        },
        {
            "measure" : "Electricity_consumtion_€",
            "value" : 0.00134,
            "unit" : "€/m2"
        }
    ]
}

So I want to add a new item to the array and assigning as "value" the value of Electricity_consumption * 0.1.

EDIT: To clarify, the problem is that Electricity_consumption is not a Constant value, it is different from one document to another. What I need is to multiply each Electricity_consumption value by the Constant 0.1 and assign its value to the new item Electricity_consumption_€.

I need to add this update to all documents in my collection.

Thanks for your help.

1 Answers1

0

To update all the documents in your collection, you can do:

const electricity_consumption = 10;

db.collection.updateMany({} ,{
    $push: {
        measures: {
            measure: "Electricity_consumtion_€",
            value: electricity_consumption * 0.1,
            unit: "€/m2"
        }
    }
})

Here we are using the $push operator to append a new object into the measures array

rantao
  • 1,621
  • 4
  • 14
  • 34
  • The problem is that Electricity_consumption is not a Constant value, it is different from one document to another. What I need is to multiply each Electricity_consumption value by the Constant 0.1 and assign its value to the new item Electricity_consumption_€. – Javier de la Iglesia Sep 22 '20 at 06:59
  • In the title of your question you say multiplication x constant – rantao Sep 22 '20 at 20:26
  • Hopefully this [question](https://stackoverflow.com/questions/8342725/multiply-field-by-value-in-mongodb) can help you – rantao Sep 22 '20 at 20:28