Note that there are some explanatory texts on larger screens.

plurals
  1. POIterating mongodb cursor serially
    text
    copied!<p>I am iterating over a collection, and for each document, I am removing an element with the lowest <code>score</code> from the <code>scores</code> array.</p> <pre><code>MongoClient.connect('mongodb://localhost:27017/school', function(err, db) { if(err) throw err; //var query = { 'assignment' : 'hw1' }; //var operator = { '$set' : { 'date_returned' : new Date() } }; var students = db.collection('students'); var updateDoc = function(document){ "use strict" console.log('update called'); db.collection('students').save(document,function(error,updatedDocument){ if(error){ console.log(error); throw error; } console.dir('successfully updated document: '+updatedDocument); }); } var cursor = students.find({}); cursor.each(function(error,doc){ "use strict" if(err) throw err; if(doc==null){ return; } doc.scores.sort(function(a,b){ return a.score-b.score; }); doc.scores.splice(0,1); updateDoc(doc); }); }); </code></pre> <p>Some of the documents are updated, but I get an error at some point like this. </p> <pre><code>{ [MongoError: E11000 duplicate key error index: school.students.$_id_ dup key: { : 0 }] name: 'MongoError', err: 'E11000 duplicate key error index: school.students.$_id_ dup key: { : 0 }'....... </code></pre> <p>I can understand that I am doing something wrong relating to asynchronous operation on the db, but I am not able to figure out the exact cause. </p> <p>Help will be appreciated. Thanks</p> <p>EDIT: document sample</p> <pre><code>{ _id: 198, name: 'Timothy Harrod', scores: [ { type: 'exam', score: 11.9075674046519 }, { type: 'quiz', score: 20.51879961777022 }, { type: 'homework', score: 55.85952928204192 }, { type: 'homework', score: 64.85650354990375 } ] } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload