1

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?

1 Answer 1

2

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

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

1 Comment

Just tested and this works beautifully, thank you! Also thank you for introducing me to mongoplayground, very helpful tool!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.