MongoDB
 SQL >> Base de données >  >> NoSQL >> MongoDB

Mettre à jour un élément précis d'un tableau de documents imbriqué avec deux correspondances

Démo – https://mongoplayground.net/p/VaE28ujeOPx

Utilisez l'opérateur positionnel $ (update) :

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

Renseignez-vous sur upsert : true.

Mise à jour

Démo – https://mongoplayground.net/p/iQQDyjG2a_B

Utilisez $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" } } } } ] )