mongodb - Group by array of document in Spring Mongo Db -
how can group tagvalu
e in spring , mongodb? mongodb query :
db.feed.aggregate([ { $group: { _id: "$feedtag.tagvalue", number: { $sum : 1 } } }, { $sort: { _id : 1 } } ])
how can same thing in spring mongodb, may using aggregation method? sample document of feed collections:
{ "_id" : objectid("556846dd1df42d5d579362fd"), "feedtag" : [ { "tagname" : "sentiment", "tagvalue" : "neutral", "modelname" : "sentiment" } ], "createddate" : "2015-05-28" }
to group tagvalue
, since array field, need apply $unwind
pipeline step before group split array can actual count:
db.feed.aggregate([ { "$unwind": "$feedtag" } { "$group": { "_id": "$feedtag.tagvalue", "number": { "$sum" : 1 } } }, { "$sort": { "_id" : 1 } } ])
the following equivalent example in spring data mongodb:
import static org.springframework.data.mongodb.core.aggregation.aggregation.*; aggregation agg = newaggregation( unwind("feedtag"), group("feedtag.tagvalue").count().as("number"), sort(asc, "_id") ); // convert aggregation result list aggregationresults<feed> results = mongotemplate.aggregate(agg, "feed", feed.class); list<feed> feedcount = results.getmappedresults();
from above, new aggregation object created via newaggregation
static factory method passed list of aggregation operations define aggregation pipeline of aggregation.
the firt step uses unwind operation generate new document each tag within "feedtag" array.
in second step group operation defines group each embedded "feedtag.tagvalue"
-value occurrence count aggregated via count aggregation operator.
as third step, sort resulting list of feedtag
tagvalue
in ascending order via sort operation.
finally call aggregate method on mongotemplate let mongodb perform actual aggregation operation created aggregation argument.
note input collection explicitly specified "feed"
parameter aggregate method. if name of input collection not specified explicitly, derived input-class passed first parameter newaggreation method.
Comments
Post a Comment