Merge all documents of collection into array

It’s not quite clear from your original post, but are you looking for a generic solution to update all at once or specific query you can apply to a document?

So you could do something like this:

db.getCollection("Test").updateMany(
{
    "_id": "DOC1"
},
[
    {
        $set:{
            newRoot:{
                _id:'$_id',
                "DOC1":['$$ROOT'],
            }
        }        
    },
    {
        $replaceRoot:{
            newRoot:'$newRoot'
        }
    }    
])

Which obviously needs you to pass in the ID so that the array can be named.

I was trying to find a generic solution where it would take a field value as the input to a field name, but could not work out a way of doing that…maybe someone else can.

1 Like