'MongoDB - Loop through array of arrays

I have a document that contains an array of arrays in my MongoDB collection.

{
    "platformId":"CMC_123",
    "carInfo":[
        ["Toyota",20,"White"],
        ["Suzuki",19,"Gray"],
        ["Ford",22,"Red"]
    ]
}

And I am expecting the below output

carMilage :{
    "Toyota":20,
    "Suzuki":19,
    "Ford":22
}

My aggregation below

[
    {
        $match:{
            platformId : "CMC_123"
        }
    },
    {
        $project:{
            carMilage : '$carInfo'
        }
    }
]

I am stuck with the $project field. How to achieve the above output using the $project field. Thank you.



Solution 1:[1]

  1. $project -

    2.1 $arrayToObject - Convert array to object with result 2.1.1.

    2.1.1 $map - Iterate carInfo array. Get the first item as k and the second item as v for the current iterated array ($$this).

db.collection.aggregate([
  {
    $match: {
      platformId: "CMC_123"
    }
  },
  {
    $project: {
      carMilage: {
        "$arrayToObject": {
          $map: {
            input: "$carInfo",
            in: {
              k: {
                $arrayElemAt: [
                  "$$this",
                  0
                ]
              },
              v: {
                $arrayElemAt: [
                  "$$this",
                  1
                ]
              }
            }
          }
        }
      }
    }
  }
])

Sample Mongo Playgound

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yong Shun