Home > Software design >  MongoDB - How to $getField from $$this for $reduce
MongoDB - How to $getField from $$this for $reduce

Time:11-18

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:

$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?

CodePudding user response:

  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

  • Related