0

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.

1 Answer 1

3
  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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.