bc110402922
bc110402922

Reputation: 457

convert array into key as a complete time and value in MongoDB

Explanation: in b we have hours, and have to complete the time and concatenate with a date. then complete date and time become as key. please see the expected outout

{
  "code": [
    {
      "a": "2016-05-10",
      "b": {
        "12": 1,
        "00": 2,
        "06": 3
      }
    },
    {
      "a": "2017-12-31",
      "b": {
        "12": 4,
        "00": 5,
        "06": 6
      }
    }
  ]
}

Expected output:

{
 "code": {
    "2016-05-10T12:00:00:0Z": 1,
    "2016-05-10T00:00:00:0Z": 2,
    "2016-05-10T06:00:00:0Z": 3,
    "2017-12-31T12:00:00:0Z": 4,
    "2017-12-31T00:00:00:0Z": 5,
    "2017-12-31T06:00:00:0Z": 6
}
}

Upvotes: 1

Views: 100

Answers (1)

turivishal
turivishal

Reputation: 36114

  • $concat to concat parts of the date
  • $reduce to iterate loop of code array and concat above processed array
db.collection.aggregate([
  {
    $set: {
      code: {
        $arrayToObject: {
          $reduce: {
            input: "$code",
            initialValue: [],
            in: {
              $concatArrays: [
                "$$value",
                {
                  $map: {
                    input: { $objectToArray: "$$this.b" },
                    as: "b",
                    in: {
                      k: {
                        $concat: ["$$this.a", "T", "$$b.k", ":00:00:0Z"]
                      },
                      v: "$$b.v"
                    }
                  }
                }
              ]
            }
          }
        }
      }
    }
  }
])

Playground

Upvotes: 1

Related Questions