MongoDB
 SQL >> Datenbank >  >> NoSQL >> MongoDB

Ein bestimmtes Element in einem verschachtelten Dokument-Array mit zwei Treffern aktualisieren

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

Verwenden Sie den positionsbasierten $ (Update)-Operator:

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

Lesen Sie bei Bedarf nach, wie upsert: true wirkt.

Update

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

Mit $function geht es ebenfalls – das ist nützlich, wenn kein passendes Element existiert und eines angelegt werden soll:

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]; // neues Dokument, falls keine notes vorhanden
          }
          var updated = false;
          for (var i=0; i < notes.length; i++) {
            if (notes[i].block == 2 && notes[i].curse == 5) {
              updated = true;
              notes[i].score.b4=40;
              break;
            }
          }
          if (!updated) notes.push(record);
          return notes;
        },
        args: [ "$notes" ],
        lang: "js"
    } } } }
  ]
)