Skip to content

Instantly share code, notes, and snippets.

@jobsamuel
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save jobsamuel/0350f3745c231f15b7a6 to your computer and use it in GitHub Desktop.

Select an option

Save jobsamuel/0350f3745c231f15b7a6 to your computer and use it in GitHub Desktop.
Playing with MongoDB - Updating documents
/////////////////////////////
/// Playing with MongoDB ///
// 3 - Updating documents /
//////////////////////////
// MongoDB Driver instance.
var MongoClient = require('mongodb').MongoClient
// Set the database and collection name you want to connect to perform the update.
, database = "college"
, collection = "students";
MongoClient.connect('mongodb://localhost:27017/' + database, function (err, db) {
if (err) throw err;
var cursor = db.collection(collection)
, temp = 0;
cursor.find().each(function(err, doc) {
if (err) {
// A simple error handler.
throw err;
// Because of reading is faster than writing,
// it's necessary to verify if there is any document to
// update in order to prevent errors while updating.
} else if (doc != null) {
// Generate a final grade from the average grade
// and a random value.
var div = 4
, n1 = doc.grades.year1
, n2 = doc.grades.year2
, n3 = doc.grades.year3
, n4 = doc.grades.year4
, n5 = Math.round(Math.random()*100)
, average = (n1 + n2 + n3 + n4) / div
, year5 = (average + n5) / 2;
// Update approved students.
if (year5 > 55) {
// Use the returned document as a criteria to find the document that is going to be updated.
cursor.update(doc, {$set: {"grades.year5": year5, approved: true} }, function (err, updated) {
// A simple error handler.
if (err) throw err;
// Count the number of updated documents in the database.
temp += 1;
// Since writing is slower than reading, it's necessary to close
// the database after all files have been updated. So, when temp
// reach 3000, which means the total documents in the collection,
// it will close the database safely.
if (temp >= 3000) {
db.close();
}
});
// Update reproved students.
} else {
cursor.update(doc, {$set: {"grades.year5": year5, approved: false} }, function (err, updated) {
// A simple error handler.
if (err) throw err;
// Count the number of updated documents in the database.
temp += 1;
// Close the database safely.
if (temp >= 3000) {
db.close();
}
});
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment