3

I am having a JSON array object something like [{_id:64,minitem:30},{},{}...] inside a variable result.. This is the result of an aggregation operation which is a projection of minimum score. I need to iterate over this result and delete the minvales from DB. I am unable to loop over the result object .. I tried

for(i=0; i<result.length; i++){ 
  db.students.update({ 
        '_id': result['_id']
      }, { 
         '$pull': { 'scores': { 'score': result[i]['minitem'] } } 
      }) 
  }

This doesnt seem to have an effect. DB is unaltered. I am trying this from mongo shell.

gmuraleekrishna
  • 3,375
  • 1
  • 27
  • 45
Prasanna Aarthi
  • 3,439
  • 4
  • 26
  • 48

1 Answers1

3
result['result'].forEach(function(doc){
    db.students.update(
        {'_id': doc._id}, 
        {'$pull':{'scores': {'score': doc.minitem }}}
    );
});

Uses the forEach function within the Mongo Shell.

Note that after aggregation the documents are actually within a result element within the return document currently.

Sammaye
  • 43,242
  • 7
  • 104
  • 146