0

I am trying to update the array: ['media_details'] with a local image path after the image has been downloaded. However using $push just added the local_url on top.

This is what ['media_details'] looks like:

"image_details": [
    {
      "processed": true,
      "position": 0,
      "seconds": "46",
      "src_url": "https://xxxxx/1.jpg",
      "image_fname": "1.jpg",
    },
    {
      "processed": true,
      "position": 1,
      "seconds": "55",
      "src_url": "https://xxxxx/2.jpg",
      "image_fname": "2.jpg",
    },

my code then downloads the image from the src_url and I want to add the local image url to the ['media_details'].

job = mongo.db.JobProcess
job.update({'_id': db_id},
                   {'$push': {
                       'image_details': {
                           'local_url': img_local_file,

                       }
                   }})

This adds the local_url to the top of the ['media_details'] - like so:

{'local_url': '/bin/static/5432ec0f-ea53-4fe1-83e4-f78166d1b9a6/1.jpg'}, 
{'local_url': '/bin/static/5432ec0f-ea53-4fe1-83e4-f78166d1b9a6/2.jpg'}, 
{'processed': True, 'position': 0, 'seconds': '46', 'src_url': 'https://xxxxx1.jpg', 'image_fname': '1.jpg'}

what I want it to do is:

 "image_details": [
        {
          "processed": true,
          "position": 0,
          "seconds": "46",
          "src_url": "https://xxxxx/1.jpg",
          "image_fname": "1.jpg",
          "local_url": "/bin/static/5432ec0f-ea53-4fe1-83e4-f78166d1b9a6/1.jpg"
        },

but which command ($set, $push, $addToSet) is best suited for updating this? and how do I implement it?

2 Answers 2

1

You need to update the image_details array item using the positional operator $. You will need a query that can uniquely identify the array item, perhaps src_url:

job.update({$and:[ 
                  {"_id": db_id},                              
                  {"image_details.src_url": img_src_url }
                  ]},
           {$set :{"image_details.$.local_url": img_local_file },
           {multi:false})
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this - I use a combination of both answers!
1

You need to use positional update operator

job.updateOne({
  '_id': db_id,
  'image_details.src_url': yourUrl,
}, {
  $set: {
    'image_details.$.local_url': img_local_file
});

1 Comment

Thank you for this - I use a combination of both answers! - but I can only give one tick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.