Dictionary to Array of Objects

Viewed 26

I have a dictionary field in my data like so:

"details": {
        "code": "PPIO",
        "product": [{
            "productCode": "ADGT"
        }]
    }

I need to convert the field to an array of objects:

"details":
        [
        {
        "code": "PPIO",
        "product": [{
            "productCode": "ADGT"
        }]
        }
        ]
1 Answers

You can use $addFields to overwrite existing field:

db.collection.aggregate([
    {
        $addFields: {
            details: [ "$details" ]
        }
    }
])

Mongo Playground

EDIT:

For update you can use below syntax:

db.col.updateMany({}, [{ $set: { details: [ "$details" ] } }])

EDIT 2: Alternatively, if updateMany doesn't work for you, you can use $out operator which will replace your collection entirely with an aggregation outcome:

db.collection.aggregate([
    {
        $addFields: {
            details: [ "$details" ]
        }
    },
    { $out: "collection" }
])
Related