Skip to content

Instantly share code, notes, and snippets.

@jgatjens
Created August 27, 2013 20:50
Show Gist options
  • Save jgatjens/6358997 to your computer and use it in GitHub Desktop.
Save jgatjens/6358997 to your computer and use it in GitHub Desktop.
Write a program that finds the document with the highest recorded temperature for each state, and adds a "month_high" field for that document, setting its value to true.
// Write a program that finds the document with the highest
// recorded temperature for each state, and adds a "month_high"
// field for that document, setting its value to true.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) {
if(err) throw err;
var cursor = db.collection('data').find({});
cursor.sort([ ['State', 1], ['Temperature', -1] ]);
var state = null;
cursor.each(function(err, doc) {
if(err) throw err;
if(doc == null) {
return db.close();
}
if (state != doc.State) {
state = doc.State;
update_weather(doc);
}
});
function update_weather(doc) {
var query = {};
query['_id'] = doc['_id'];
doc['month_high'] = true;
db.collection('data').update(query, doc, function(err, updated) {
if(err) throw err;
console.dir("Successfully updated " + updated + " document!");
return db.close();
});
}
});
@deepakdogra
Copy link

we got an error while running above program-- mongo Error connection closed by application

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment