通过乘以字段将行分组并返回其他字段

问题描述 投票:0回答:1

我想通过乘以字段来对行进行分组,并返回其他字段,就像在我的示例中一样,但是它不起作用。

db.collection.aggregate([
        {'$group': {'_id': {
            '$basic.last_name',
            '$basic.first_name'
        }, 'data': {'$last': '$$ROOT'}}},
        {'$replaceRoot': {'newRoot': '$data'}}
    ])

此变体例外,我只需要按两个字段分组:

db.collectio.aggregate([
        {'$group': {'_id': {'$basic.last_name', 'data': {'$last': '$$ROOT'}}},
        {'$replaceRoot': {'newRoot': '$data'}}
    ])

我如何实现目标?谢谢!

mongodb mongodb-query aggregation-framework
1个回答
0
投票

您快要接近了,代码语法错误:

db.collection.aggregate([
    {'$group': {'_id': {
        'last_name': '$basic.last_name',
        'first_name': '$basic.first_name'
    }, 'data': {'$last': '$$ROOT'}}},
    {'$replaceRoot': {'newRoot': '$data'}}
])
© www.soinside.com 2019 - 2024. All rights reserved.