Reputation: 11
Within my Meteor application, I have a document (from the mongo collection) for which a portion of the data within it is an array of objects.
I have created a loop that goes through the array of objects, uses information from the object within each array index to calculate new data points. (specifically, using a mean to calculate variance and standard deviation).
I then want to update the object, at that array index, to include the new data points (variance and standard deviation).
JSON object:
"row_sum" : [
{
"name" : "Total Inches of Rainfall",
"row_int" : 1,
"mean" : 14.492753623188406
},
{
"name" : "Inches Above/Below (+/-)135 Year Average",
"row_int" : 2,
"mean" : 0.13043478260869565
}
],
My desired output is:
"row_sum" : [
{
"name" : "Total Inches of Rainfall",
"row_int" : 1,
"mean" : 14.492753623188406
"variance" : 1234,
"sd" : 1111
},
{
"name" : "Inches Above/Below (+/-)135 Year Average",
"row_int" : 2,
"mean" : 0.13043478260869565,
"variance" : 1234,
"sd" : 1111
}
],
Here's my current output:
"row_sum" : [
{
"name" : "Total Inches of Rainfall",
"row_int" : 1,
"mean" : 14.492753623188406
},
{
"name" : "Inches Above/Below (+/-)135 Year Average",
"row_int" : 2,
"mean" : 0.13043478260869565
},
{
"variance" : 48.24328113588513,
"sd" : 6.945738343465375
},
{
"variance" : 48.024652540384196,
"sd" : 6.929982145747866
}
],
As you can see, it's simply appending the data as a new object within the array of objects, rather than updating the specific object indexed within the array's loop.
Here's the section of code that contains the loop and the Mongo Update command:
for (var i = 0; i < row_sum.length; i++){
var variance = this.calculate_variance(data_summary_id, row_sum[i]);
var standard_deviation = Math.sqrt(variance);
var sum_data = {
row_sum : {
variance: variance,
sd: standard_deviation
}
}
DataSetSummary.update(data_summary_id, {$push: sum_data});
}
Upvotes: 1
Views: 281
Reputation: 8335
Try $set method and positional operator $ . Use the following query
db.test.update({"row_sum.row_int":1},{$set:"row_sum.$.variance":1,"row_sum.$.sd" : 6.9}})
Since it is an element in row you will have to use positional arguments try the following question for more answer
Upvotes: 1