Search code examples
arraysruby-on-railsrubymongoid

How to convert an array to a hash using Mongoid Pipeline?


Given a pipeline that emits an array of hashes.

Each indicators key has a value of an array:

[{
  "indicators" => [
     "SMA:1",
     "SMA:2",
     "SMA:3" ]},
  ...

How to use a pipeline to convert the indicators array to a hash to get:

[{
  "indicators" => {
     "SMA:1" => true,
     "SMA:2" => true,
     "SMA:3" => true }},
 ...

Solution

  • Use $map to map your array from ['v1', 'v2', 'v3'] to [['v1', true], ['v2', true], ['v3', true]], then use https://docs.mongodb.com/manual/reference/operator/aggregation/arrayToObject/ to convert that to a hash.