简体   繁体   中英

Merging nested object fields into a single nested array field in MongoDB Aggregation

As part of my aggregation pipeline I have the following scenario. This is the result of grouping previously unwound fields from each document (so in this case there are two documents with the same _id but with a different value for UniqueFieldName)

    TopLevelField: [
        {
            UniqueFieldName: "Values go here!"
        },
        {
            UniqueFieldName: "More values go here too!"
        }
    ]

All I want to do is merge the nested object fields into one field and push all the values into that field as an array, like so.

    TopLevelField: {
        UniqueFieldName: [
             "Values go here!",
             "More values go here too!",
        ],
    }

The idea is that I could have multiple fields with multiple values under each field grouped together for easier iteration.

    TopLevelField: {
        UniqueFieldName: [
             "Values go here!",
             "More values go here too!",
        ],
        SecondFieldName: [
             "This is text",
        ],
        AnotherOne: [
             "TEXT",
             "Here too!",
             "More values",
        ],
    }

The problem I run into is that trying to use dot notation in the $group stage throws an error. It seems that mongo doesn't like to group with nested objects like this?

The easy solution is to just change the TopLevelField to some concatenation of the nested fields like this,

    TopLevelField-UniqueFieldName: [
         "Values go here!",
         "More values go here too!",
    ],
    TopLevelField-SecondFieldName: [
         "This is text",
    ],
    TopLevelField-AnotherOne: [
         "TEXT",
         "Here too!",
         "More values",
    ],

But this is suboptimal for my use case. Is there a solution to this or do I need to rethink the entire pipeline?

You can try this:

db.collection.aggregate([
    { $unwind: '$TopLevelField' },
    {
        $group: {
            _id: '', 'UniqueFieldName': { $push: '$TopLevelField.UniqueFieldName' },
            'UniqueFieldName2': { $push: '$TopLevelField.UniqueFieldName2' },
            'UniqueFieldName3': { $push: '$TopLevelField.UniqueFieldName3' },
            'UniqueFieldName4': { $push: '$TopLevelField.UniqueFieldName4' }
        }
    }, { $project: { _id: 0 } }, { $project: { 'TopLevelField': '$$ROOT' } }])

Test: MongoDB-Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM