1

I want to be able to: Find a document with a specific id, then find the document in the legacy array based off a shortID, and update the sets array of that embedded document that matched the shortID.

Clearly, something hasn't clicked for me yet.

I have the following structure:

  {
    "id" : "5706e5b5cbc61e5bf3a9f4e7",
    "legacy" : [
        {
            "shortID" : "B1zHAllg",
            "timeStamp" : "Apr 16th 2016",
            "sets" : [
                {
                    "weight" : "7",
                    "reps" : "7"
                },
                {
                    "weight" : "7",
                    "reps" : "7"
                }
            ]
        },
        {
            "shortID" : "HyUVCegx",
            "timeStamp" : "Apr 16th 2016",
            "sets" : [
                {
                    "weight" : "6",
                    "reps" : "6"
                },
                {
                    "weight" : "6",
                    "reps" : "6"
                }
            ]
        }
    ]
 }

I have tried many options but felt I was closest with trying the following:

db.bench.findAndModify({query:{id:"5706e5b5cbc61e5bf3a9f4e7"},sort:{legacy:{$elemMatch:{shortID:"HyUVCegx"}}},update:{$set:{sets:[9]}}})

db.bench.update({id : "5706e5b5cbc61e5bf3a9f4e7", legacy:{$elemMatch:{shortID:"HyUVCegx"}}}, {$set : { sets: [{"weight":"5", "reps" :"10"}] }})

1 Answers1

1

You'll want to use positional updates for this kind of operations. See documentation for positional updates

Example: In MongoDB shell, you'll be doing as:

db.collection.updateOne(
{"legacy.shortID":"HyUVCegx"}, 
{$set:
  {"legacy.$.sets":
    [{"weight":"15", "reps" :"10"}]
  }
})

Query above will modify content of documents in legacy matching criteria where shortID = "HyUVCegx"

Saleem
  • 8,728
  • 2
  • 20
  • 34