問題描述
對列表進行排序並在 mongodb 中插入一個新列 (Sort the list and insert a new column in mongodb)
I need to sort states and figure out the highest temperature for each state in this weather data residing in mongodb.
How do I iterate through each record in Javascript and insert a new column 'month_highest' when I figure out the highest temperature for that state ?
Day Time State Airport Temperature Humidity WindSpeed
1 54 Vermont BTV 39 57 6
1 154 Vermont BTV 39 57 4
1 254 Vermont BTV 39 57 5
1 354 Vermont BTV 38 70 5
1 454 Vermont BTV 34 92 11
16 53 Florida ORL 46 71 9 16 153 Florida ORL 47 71 8 16 253 Florida ORL 46 73 8 16 353 Florida ORL 47 74 8 16 453 Florida ORL 46 79 7 16 553 Florida ORL 46 79 5 16 653 Florida ORL 46 83 4
參考解法
方法 1:
MongoDB Map‑Reduce
db.temps.mapReduce(
/* map */
function() {
emit( this.State, this.Temperature);
},
/* reduce */
function key(key, values) {
var ret = 0;
for (var i=0; i<values.length, i++) {
if (values[i] > ret) ret = values[i];
}
return ret
},
/* params */
{
query: {
DateTime: {
$gte: new Date('2013‑01‑01')
,$lt: new Date('2013‑02‑01')
}
}
,sort: {
State:1
}
}
);
As for inserting a new month‑max, that depends on how you want to store it? How are you querying this data?
You could output the results into a new collection, or use that programmatically to update another collection. It depends on how you want your data shaped. It actually looks like you are really flat with your data as it stands.