MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

aggiorna l'elemento specifico dall'array di documenti nidificato mongodb dove ha due corrispondenze

Demo - https://mongoplayground.net/p/VaE28ujeOPx

Usa $ (aggiornamento)

db.collection.update({
  "notes": {
    "$elemMatch": { "block": 2, "curse": 5 }
  }
},
{
  $set: { "notes.$.score.b4": 40 }
})

Leggi upsert :vero

Aggiorna

Demo - https://mongoplayground.net/p/iQQDyjG2a_B

Usa $function

db.collection.update(
    { "_id": "sad445" },
    [
      {
        $set: {
          notes: {
            $function: {
              body: function(notes) {
                        var record = { curse:5, block:2, score:{ b4:40 } };
                        if(!notes || !notes.length) { return [record]; } // create new record and return in case of no notes
                        var updated = false;
                        for (var i=0; i < notes.length; i++) {
                            if (notes[i].block == 2 && notes[i].curse == 5) { // check condition for update
                                updated = true;
                                notes[i].score.b4=40; break; // update here
                            }
                        }
                        if (!updated) notes.push(record); // if no update push the record in notes array
                        return notes;
                    },
              args: [
                "$notes"
              ],
              lang: "js"
            }
          }
        }
      }
    ]
)