在 MongoDB 中更改 $sum 结果类型

Change $sum result type in MongoDB

这是我的查询:

db.log.aggregate([{
    $match: {
        "meta.userId": {
            $exists: true,
            $ne: null
        },
        "timestamp": {
            $gte: ISODate("2016-01-01"),
            $lte: ISODate("2016-01-07")
        }
    }
}, {
    $group: {
        _id: "$meta.userId",
        count: {
            $sum: 1
        }
    }
}])

在聚合管道中使用 { $sum: 1 } 时,shell return 是 double。我希望它直接 return 一个 整数 因为它只是文档的计数。

{
"result" : [ 
    {
        "_id" : "foo",
        "count" : 46.0000000000000000
    }, 
    {
        "_id" : "foo1",
        "count" : 146.0000000000000000
    }
],
"ok" : 1.0000000000000000
}

知道如何更改总和的类型吗?

我的 MongoDB 版本是 3.0.7。我使用 Robomongo 0.8.5.

谢谢!

您可以使用 NumberInt 明确指定值 1 是一个整数,请参阅此 JIRA 票证。当 MongoDB shell 中的 运行 类似查询时通常不需要此功能,因此这可能是 Robomongo 的一个功能。

db.log.aggregate([{
    $match: {
        "meta.userId": {
            $exists: true,
            $ne: null
        },
        "timestamp": {
            $gte: ISODate("2016-01-01"),
            $lte: ISODate("2016-01-07")
        }
    }
}, {
    $group: {
        _id: "$meta.userId",
        count: {
            $sum: NumberInt(1)
        }
    }
}])