Mongo DB数组聚合,用于计算集合中的所有数组条目

时间:2017-06-21 20:49:18

标签: arrays mongodb

我有一个看起来像的集合:

{
    "_id" : ObjectId("58b77d1349b2e11c06d9cb8a"),
    "blocks" : [
        {
            "userId" : ObjectId("5893a9a64ce29f0231bd060c"),
            "_id" : ObjectId("58b786c5665532d53c21ac72"),
        }
    ]
}
{
    "_id" : ObjectId("58b77d1349b2e11c06d9cb8c"),
    "blocks" : [
        {
            "userId" : ObjectId("581bbb0422e3911e24ea0276"),
            "_id" : ObjectId("592f2d8f092b3b6e374d9bec"),
        }
    ],
}
{
    "_id" : ObjectId("58b85e16894bf623065a0899"),
    "blocks" : [
        {
            "userId" : ObjectId("56e086538146ecb412f974e9"),
            "_id" : ObjectId("592f2cb506dc59992009424a"),
        }
    ]
}

我想总结集合中所有“块”数组中的元素数量,所以我在shell中选择了一个聚合查询:

db.userblocks.aggregate([
    {
        $match: {
            blocks: { $gt: [] }
        }
    },
    {
        $group: {
            _id: null,
            cntArray: {
                $push: { $size: "$blocks" }
            }
        }
    },
    {
        $project: {
            "num_blocks": {
                $reduce: {
                    input: "$cntArray",
                    initialValue: 0,
                    in: { $add: [ "$$value", "$$this" ] }
                }
            }
        }
    }
])

问题是聚合查询失败并显示错误:

Error: command failed: { "ok" : 0, "errmsg" : "invalid operator '$reduce'", "code" : 15999 } : aggregate failed

documentation,我所做的似乎是有效的,但我似乎无法弄清楚我做错了什么。

0 个答案:

没有答案