Home > Mobile >  MongoDB - Set field to hash of another field
MongoDB - Set field to hash of another field

Time:11-03

Is there a way to run this query so that instead of { $toString: "$_id" } I can take the hash of the image field value for that document and set the field to that hash value?

So instead of this:

    db.getCollection("test_products").updateMany( {_id: {$in: [ ObjectId('6340eae3bb965cdee37b8b30'), ObjectId('6340eae3bb965cdee37b8b33') ]}}, [
    { $set : { image : { $concat : [ "https://www.example.com/products/", { $toString: "$_id" }, ".png" ] } } }
    ] );

I would want something like this:

    db.getCollection("test_products").updateMany( {_id: {$in: [ ObjectId('6340eae3bb965cdee37b8b30'), ObjectId('6340eae3bb965cdee37b8b33') ]}}, [
    { $set : { image : { $concat : [ "https://www.example.com/products/", { $hex_md5: "$image" }, ".png" ] } } }
    ] );

CodePudding user response:

You will need to use $function to use js functionality for the md5 sum computation.

db.collection.update({},
[
  {
    "$addFields": {
      "image": {
        "$function": {
          "body": "function(image){return \"https://www.example.com/products/\" hex_md5(image) \".png\"}",
          "args": [
            "$image"
          ],
          "lang": "js"
        }
      }
    }
  }
],
{
  multi: true
})

Mongo Playground

  • Related