Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB – How to $getField from $$this for $reduce

I would like to move an array stored in old_field that looks like this:

[{id: "XXX", ...}, {"id": "YYY", ...}, ...]

Into new_field looking like this:

{"XXX": {id: "XXX", ...}, "YYY":, {id: "YYY", ...}, ...}

As such, I attempted to do a few iterations of the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$addFields: {
  new_field: {
    $reduce: {
      input: "$old_field",
      initialValue: {},
      in: {
        {$getField: {field: "id", input: "$$this"}}: "$$this"
      }
    }
  }
}

All of which failed. Note that doing:

$addFields: {
  new_field: {
    $reduce: {
      input: "$old_field",
      initialValue: {},
      in: {
        "1": {$getField: {field: "id", input: "$$this"}}
      }
    }
  }
}

Returns a new_field w/ value 1: {the_correct_id_here}, so I know that the $getField works properly (besides likely using $$this in the wrong context).

Why isn’t $getField working in this context? How would I go about doing this transformation?

>Solution :

  1. $addField

    1.1. $arrayToObject – Convert the array result from 1.1.1 to object.

    1.1.1. $map – Iterate each element in the old_field array and return a new array. Convert each element to an object with k and v properties.

db.collection.aggregate([
  {
    $addFields: {
      new_field: {
        $arrayToObject: {
          $map: {
            input: "$old_field",
            in: {
              k: "$$this.id",
              v: "$$this"
            }
          }
        }
      }
    }
  }
])

Demo @ Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading