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

1 Answer 1

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"

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you so much Saleem!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.