mongodb 如何同时修改单个文档中的多个数组的元素?



  • 假设有集合中文档有如下如下格式:
    {
        "_id":1,
        "name":"zhangsan",
        "scores":[
            {
                "year":"2000",
                "courses_scores":[
                       {"course":"chinese","score":80},
                       {"course":"maths","score":85},
                       {"course":"english","score":76}
                 ]
            },
            {
                "year":"2001",
                "courses_scores":[
                       {"course":"chinese","score":78},
                       {"course":"maths","score":82},
                       {"course":"english","score":81}
                 ]
            }
        ]
    }
    如何同时修改year="2000"、course="chinese"的score,和year="2001"、course="english"的score?


  • Lv 1

    @x4_965be

    db.b.find({}).map( function(d){
      for(var j=0, jc=d.scores.length;j<jc;++j){
        var score = d.scores[j];
        if(score.year == 2000){
           for(var e = score.courses_scores, c=e.length,i=0;i<c;++i){
             if(e[i].course == 'chinese'){
               e[i].score = 0;
             }
           }
           continue;
        }
        
        if(score.year == 2001){
          for(var e = score.courses_scores, c=e.length,i=0;i<c;++i){
             if(e[i].course == 'english'){
    e[i].score = 0;
             }
           }
           continue;
        }
      }
      db.b.save(d);
    });

登录后回复
 

与 萌阔论坛 的连接断开,我们正在尝试重连,请耐心等待