简体   繁体   中英

Spring data equivalent of below aggregation operation in mongodb

I have a "product" collection which has a "category" field. I am trying to get count of distinct categories. I can't use db.product.distinct("category").length as it exceeds 16mb cap with below error:-

> 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

So,I am using aggregation framework for this and I am able to get count using this query:-

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

I am not able to translate this into spring data mongodb aggregation query. Please help. I am getting following errors with what I have tried:

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

Error: AggregationField can't be null. I have tried other strings in second group operation but it gives Invalid reference error.

The better way to write what you are writing here would be in the shell form:

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

Which provides a total count per category.

What your query form does as it throws the grouping part away and just counts the distinct terms. But this would be how you really write it, as this is just a fluke that in JavaScript the "string" which is not a variable evaluates to null :

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

In which case your spring data way of writing this is:

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

The System.out. there shows you the correctly formed statement.

Try it in the shell. There is no difference between "" and " " or "aaaa" without a prefixing "$", which is what makes it a field reference. Spring data treats the "string" as a field, so not supplying one equals null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM