找不到 Mongodb $count聚合管道



我正在尝试在Mongo中构建一个聚合管道,以计算在相当大的数据集中每10分钟生成的文档数量。 每个文档在名为requestDtsCal的字段中包含一个ISODate。 我正在尝试以下代码(感谢 https://stackoverflow.com/users/3943271/wizard 的基本代码(:

var baseDate = new Date(2017, 01, 11, 00, 00, 0);
var startDate = new Date(2017, 01, 11, 00, 00, 0);
var endDate = new Date(2018, 09, 20, 14, 25, 0);
var divisor = 10 * 60 * 1000; // 10 minutes in miliseconds
db.AUDIT.aggregate([ 
    {
        $match : {
            requestDtsCal : {
                $gte : startDate,
                $lt : endDate
            }
        }
    }, {
        $group : {
            _id : {
                $subtract : [ "$requestDtsCal", {
                    $mod : [ {
                        $subtract : [ "$requestDtsCal", baseDate ]
                    }, divisor ]
                } ]
            },
            dates : {
                $push : "$requestDtsCal"
            }
        }
    }, {
        $count: "$requestDtsCal"
    } 
]).pretty();

如果我在没有最后一个管道阶段的情况下运行它,它会返回每个范围内每个文档的所有日期的数组数组。 一旦我尝试在最后一个管道阶段计算每个范围内的文档数量,它就会失败:

assert: command failed: {
    "ok" : 0,
    "errmsg" : "Unrecognized pipeline stage name: '$count'",
    "code" : 16436
} : aggregate failed
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:16:14
assert.commandWorked@src/mongo/shell/assert.js:403:5
DB.prototype._runAggregate@src/mongo/shell/db.js:260:9
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1212:12
@(shell):1:1
2018-01-18T19:54:40.669-0800 E QUERY    [thread1] Error: command failed: {
    "ok" : 0,
    "errmsg" : "Unrecognized pipeline stage name: '$count'",
    "code" : 16436
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:16:14
assert.commandWorked@src/mongo/shell/assert.js:403:5
DB.prototype._runAggregate@src/mongo/shell/db.js:260:9
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1212:12
@(shell):1:1

知道我做错了什么吗? 这是针对Mongo 3.2.11 FWIW运行的。

谢谢

伊恩

如果版本为 3.2,则可以在管道中使用$sum $group以获取计数

而不是

{ $count: "$requestDtsCal" } 

{$group : {_id : null, count : {$sum : 1}}} // _id your ids

我想出了一种简单的方法来做到这一点。 我没有正确理解群体。

var baseDate = new Date(2017, 01, 11, 00, 00, 0);
var startDate = new Date(2017, 01, 11, 00, 00, 0);
var endDate = new Date(2018, 09, 20, 14, 25, 0);
var divisor = 10 * 60 * 1000; // 10 minutes in miliseconds
db.AUDIT.aggregate([ 
    {
        $match : {
            requestDtsCal : {
                $gte : startDate,
                $lt : endDate
            }
        }
    }, {
        $group : {
            _id : {
                $subtract : [ "$requestDtsCal", {
                    $mod : [ {
                        $subtract : [ "$requestDtsCal", baseDate ]
                    }, divisor ]
                } ]
            },
            count: {$sum: 1}
        }
    }
]).pretty();

工作正常。

伊恩

最新更新