Mongo复合聚合(基于组计数的条件)

时间:2015-08-17 16:24:30

标签: mongodb mongodb-query aggregation-framework

我需要一个给出样本数据的mongo聚合:

{
    'employeeNumber': '1',
    'companyId': '1',
    'role': 'D',
    'dateHired':ISODate("2013-11-26T00:00:00.0Z")
    ...
}
{
    'employeeNumber': '1',
    'companyId': '1',
    'role': 'S',
    'dateHired':ISODate("2013-11-26T00:00:00.0Z")
    ...
}
{
    'employeeNumber': '1',
    'companyId': '2',
    'role': 'D',
    'dateHired':ISODate("2013-11-26T00:00:00.0Z")
    ...
}
{
    'employeeNumber': '2',
    'companyId': '1',
    'role': 'D',
    'dateHired':ISODate("2013-11-26T00:00:00.0Z")
    ...
}

查询给定的companyId(例如companyId = 1,可能使用匹配阶段)并返回类似的内容:

{    
    'employeeNumber': '1',
    'companyId': '1',
    'role': 'D','S'
    'dateHired':ISODate("2013-11-26T00:00:00.0Z")
    ...
}

注意

{    
    'employeeNumber': '1',
    'companyId': '2',
    'role': 'D'
    'dateHired':ISODate("2013-11-26T00:00:00.0Z")
    ...
}

未退回。

理想情况下,它会返回整个对象,因为集合有10/12个字段。

1 个答案:

答案 0 :(得分:1)

使用aggregation您将无法获得准确的预期输出,但您可以获得如下输出:

{ "role" : [ "D" ], "employeeNumber" : "2" }
{ "role" : [ "S" ], "employeeNumber" : "3" }
{ "role" : [ "D", "S" ], "employeeNumber" : "1" }

查询将如下:

db.collection.aggregate({
    $group: {
    _id: "$employeeNumber",
    "role": {
        "$push": "$role"
    }
    }
}, {
    $project: {
    "employeeNumber": "$_id",
    "role": 1,
    "_id": 0
    }
})

修改问题编辑后:

db.collection.aggregate({
    $group: {
    _id: {
        employeeNumber: "$employeeNumber",
        "companyId": "$companyId"
    },
    "role": {
        "$push": "$role"
    },
    "dateHired": {
        $last: "$dateHired"
    }
    }
}, {
    $project: {
    "employeesNumber": "$_id.employeeNumber",
    "comapnyId": "$_id.companyId",
    "role": 1,
    "dateHired": 1,
    "_id": 0
    }
})