Bitsplease
Bitsplease

Reputation: 306

Using MongoDB Aggregation to merge two lists into an object

I'm using mongoDB and I have documents similar to the following

{
  "files": ["Customers", "Items", "Contacts"],
  "counts": [1354, 892, 1542],
  ...
}

And using an aggregation pipeline stage, I want to convert the above into something more like..

{
  "file_info": [
    {"file_name": "Customers", "record_counts": 1354},
    {"file_name": "Items", "record_counts": 892},
    {"file_name": "Contacts", "record_counts": 1542}
  ]
}

I've tried using $map, $reduce, and $arrayToObject but without any success. What operators can I use to get from where I currently am to where I need to be?

Upvotes: 1

Views: 355

Answers (1)

mickl
mickl

Reputation: 49985

You can use $zip to combine two arrays and $map to get the new structure:

{
    $project: {
        file_info: {
            $map: {
                input: { $zip: { inputs: [ "$files", "$counts" ] } },
                in: {
                    file_name: { $arrayElemAt: [ "$$this", 0 ] },
                    record_counts: { $arrayElemAt: [ "$$this", 1 ] },
                }
            }
        }
    }
}

Mongo Playground

Upvotes: 2

Related Questions