Search code examples
mongodbnosqlmongodb-queryaggregation-frameworknosql-aggregation

Mogodb aggregation create output as {"key": "value"} from 2 arrays


I have a question about how to create output from 2 arrays one array with translation key and another with translation i would output as

"translation_key":"value"  

Current output:
{

        "_id" : ObjectId("5bfc0b2b30c4683f585078fb"),
        "translation" : [ 
            "hour", 
            "day"

        ],
        "translation_key" : [ 
            "HOUR_TEXT", 
            "DAY_TEXT"  


        ],
        "locale_id" : "EN_en"
   }

OUTPUT should be :

{
    "EN_en" :{
        "HOUR_TEXT" :"hour",
        "DAY_TEXT" :"day",
    }
}

Solution

  • You can try below aggregation:

    db.col.aggregate([
        {
            $project: {
                array: [
                    {
                        k: "$locale_id",
                        v: {
                            $arrayToObject: {
                                $map: {
                                    input: { $range: [0, { $size: "$translation" }] },
                                    as: "index",
                                    in: {
                                        k: { $arrayElemAt: [ "$translation", "$$index" ] },
                                        v: { $arrayElemAt: [ "$translation_key", "$$index" ] }
                                    }
                                }
                            }
                        }
                    }
                ]
            }
        },
        {
            $replaceRoot: {
                newRoot: { $arrayToObject: "$array" }
            }
        }
    ])
    

    Basically you need to use $arrayToObject operator to manipulate your key names and in your case it should be used twice. This operator expects an array of objects with two properties k and v and therefore you should use $map to generate that values based on translation, $range is used to generate indexes to traverse translation and translation_key arrays. Then you can use $replaceRoot to promote dynamically generated key into root level of your document.

    Output:

    { "EN_en" : { "hour" : "HOUR_TEXT", "day" : "DAY_TEXT" } }