Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB aggregation: Aggregate array into keyed objects

I'd like to flatten document array into a keyed objects using the aggregation functionality. Here’s an example of my documents:

[ 
    {
        "_id": 1,
        "texts": [
            { "language": "english", "text": "hello" },
            { "language": "german", "text": "hallo" },
            { "language": "french", "text": "bonjour" }
        ]
    }, …
]

Expected result:

[
     {
        "_id": 1,
        "texts": {
            "english": "hello",
            "german": "hallo",
            "french": "bonjour"
        }
    }, …
]

I’ve looked at different operators, e.g. $map, but this seems to be focued on transforming array to array. I’d probably need a JS equivalent of $reduce, but couldn’t find a way of accumulating my values into an object.

Any ideas?

like image 855
qqilihq Avatar asked Aug 05 '26 08:08

qqilihq


1 Answers

You need $map and $arrayToObject which converts an array of k-v pairs into single object:

db.col.aggregate([
    {
        $addFields: {
            texts: {
                $arrayToObject: {
                    $map: {
                        input: "$texts",
                        as: "text",
                        in: {
                            k: "$$text.language",
                            v: "$$text.text"
                        }
                    }
                }
            }
        }
    }
])
like image 96
mickl Avatar answered Aug 08 '26 00:08

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!