Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ahmetonurslmz/de336e529be87a48d413236f9735e9c9 to your computer and use it in GitHub Desktop.
Save ahmetonurslmz/de336e529be87a48d413236f9735e9c9 to your computer and use it in GitHub Desktop.
Updating nested array inside array mongodb

Updating nested array inside array mongodb

For example: We have a document like this one;

clubs:{
cid: 1,
cname: "Fenerbahce",
cplayers: [{
   pid: 1,
   pad: "Elif Elmas",
   pgoals: [{
          gid: 1,
          gtime: 2019-06-20T16:12:51.989+00:00,
          gtype: "thisone"
          }]
        }]
   }

We must use this structure to update document's pgoals array:

const { body : { cid,pid,gid } } = req;
clubs.update(
        {
            "cid": cid,
            "cplayers": {
                "$elemMatch": {
                    "pid": pid, "pgoals.gid": gid
                }
            }
        },
        { "$set": { 
            "cplayers.$[outer].pgoals.$[inner].gtype": "thisoneUpdated"
        } },
        { "arrayFilters": [
            { "outer.pid": pid },
            { "inner.gid": gid }
        ] }, (err, result) => {
        if (err) {
            console.log('Error updating service: ' + err);
            res.send({'error':'An error has occurred'});
        } else {
            console.log(result)
        }
    });
@ashish-primetech
Copy link

:)

@yngfoxx
Copy link

yngfoxx commented Jan 20, 2023

😌 just what I needed (in Mario's voice)

@mrund3ad1
Copy link

Helped Alot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment