Mongodb Aggregation - I have the data, now how to map it for correct output?

Viewed 27

I have two collections: Review and Game. I'm trying to make a query for "Games reviewed today" in Mongodb. So far, I've got everything working pretty well. The only issue is the final formating.

db.Review.aggregate([
        {
            $match: {
                publishedDate: {
                    $gte: cutoff
                }
            }
        }, {
            $sortByCount: '$game.id'
        }, {
            $limit: 10
        }, {
            $lookup: {
                from: 'Game',
                localField: '_id',
                foreignField: 'id',
                as: 'game'
            }
        }, {
            $project: {
                'game.id': 1,
                'game.name': 1,
                'game.topCriticScore': 1,
                'game.firstReleaseDate': 1,
                'game.tier': 1,
                '_id': 0
            }
        }
    ]);

This returns a result with the following format:

[
    {
        "game": [
            {
                //document
            }
        ]
    },
    {
        "game": [
            {
                //document
            }
        ]
    },
    {
        "game": [
            {
                //document
            }
        ]
    }
]

Overall, this is great! I have all the data I need. However, it's not formatted how I'd like it to be.

I know if I was using Javascript, I'd just make this my last line of code:

results.map(result => result.game[0])

Is there a way to achieve this mapping?

1 Answers

You can use $arrayElemAt to get first element and $replaceRoot to promote it to root level:

db.collection.aggregate([
    {
        $replaceRoot: {
            newRoot: { $arrayElemAt: [ "$game", 0 ] }
        }
    }
])

Mongo Playground

Related