我有一个“产品”集合,其中有一个“类别”字段。我试图获得不同类别的计数。
我无法使用db.product.distinct(“ category”)。length,因为它超过了16mb上限,并出现以下错误:-

> db.product.distinct("category").length
2014-07-21T08:58:25.289-0400 distinct failed: {
    "errmsg" : "exception: distinct too big, 16mb cap",
    "code" : 17217,
    "ok" : 0
} at src/mongo/shell/collection.js:1108


所以,我为此使用聚合框架,我可以使用此查询来计数:-

db.product.aggregate([{$group: {_id:"$category"}}, {$group: {_id:"", count:{$sum:1}}}], {allowDiskUse: true})


我无法将其转换为spring数据mongodb聚合查询。请帮忙。
我尝试了以下错误:

        Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.group("category"),
        Aggregation.group(" ").count().as("numDistinctCategories"));


错误:AggregationField不能为null。
我在第二组操作中尝试了其他字符串,但它给出了无效的引用错误。

最佳答案

在这里写东西的更好的方法是shell形式:

db.product.aggregate([
    {"$group": { "_id": "$category", "count": { "$sum": 1 } } }
])


其中提供了每个类别的总数。

您的查询表单会做什么,因为它将分组部分丢掉了,只计算了不同的术语。但这就是您真正编写它的方式,因为这只是JavaScript幸,在JavaScript中,不是变量的“字符串”的结果为null

db.product.aggregate([
    { "$group": { "_id": "$category" } },
    { "$group": { "_id": null, , "count": { "$sum": 1 } } }
])


在这种情况下,您的spring数据编写方式为:

    Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.group("category"),
            Aggregation.group().count().as("count")
    );
    System.out.println(aggregation);


此处的System.out.显示正确格式的语句。

在外壳中尝试一下。没有前缀“ $”的“”和“”或“ aaaa”之间没有区别,这就是使其成为字段引用的原因。 Spring数据将“字符串”视为字段,因此不提供等于null的值

10-08 16:29