【问题标题】:Change $sum result type in MongoDB在 MongoDB 中更改 $sum 结果类型
【发布时间】:2016-01-08 09:38:25
【问题描述】:

这是我的查询:

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 返回一个double。我希望它直接返回一个整数,因为它只是一个文档计数。

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

知道如何更改 sum 的类型吗?

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

谢谢!

【问题讨论】:

    标签: mongodb robo3t


    【解决方案1】:

    您可以使用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)
            }
        }
    }])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-14
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 2011-11-16
      • 1970-01-01
      • 2012-05-19
      相关资源
      最近更新 更多