Mongodb Aggregation-我有数据,现在如何将其映射为正确的输出?

时间:2019-06-19 13:30:20

标签: mongodb aggregation-framework

我有两个收藏夹:Review和Game。我正在尝试在Mongodb中查询“今天回顾的游戏”。到目前为止,我一切都很好。唯一的问题是最终格式。

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
            }
        }
    ]);

这将返回以下格式的结果:

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

总体来说,太好了!我拥有所需的所有数据。但是,它没有按照我的意愿进行格式化。

我知道我是否在使用Javascript,我只是将其作为最后一行代码:

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

有没有办法实现这种映射?

1 个答案:

答案 0 :(得分:1)

您可以使用$arrayElemAt获取第一个元素,并使用$replaceRoot将其提升到根级别:

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

Mongo Playground