Home > Back-end >  MongoDB - Loop through array of arrays
MongoDB - Loop through array of arrays

Time:05-14

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.

CodePudding user response:

  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

  • Related