我该如何在Mongoldb女巫中聚合返回主题和主题数

时间:2019-03-23 15:32:58

标签: java mongodb aggregation

我在mongodb中有一个数据库,该数据库具有三个字段,一个是pageID,注释,另一个是日期。

我需要汇总所有相同的pageID并按日期降序返回pageID的数量计数。我需要在Java中执行此操作。获取相同的pageId计数。

{ "_id" : ObjectId("5c93b148e3c73c03bb9b528b"), "idPagina" : "23", "date" : ISODate("2019-03-21T15:44:08.434Z"), "email" : "edw@jreww.com", "body" : "adnalf" }
{ "_id" : ObjectId("5c93bf4ae3c73c0598e94b44"), "idPagina" : "45", "date" : ISODate("2019-03-21T16:43:53.695Z"), "email" : "ewfn@fewr.com", "body" : "jklewnf" }
{ "_id" : ObjectId("5c93fb6fe3c73c054600c983"), "idPagina" : "78", "date" : ISODate("2019-03-21T21:00:30.882Z"), "email" : "raphael@me.com", "body" : "jhsdbclkdbclkd" }

尝试汇总,但我需要转换为java:

db.posts.aggregate([{$group : {_id : "$idPagina", num_posts : {$sum : 1}}}])
{ "_id" : "60", "num_posts" : 1 }
{ "_id" : "56", "num_posts" : 1 }
{ "_id" : "23", "num_posts" : 31 }
{ "_id" : "30", "num_posts" : 1 }
{ "_id" : "78", "num_posts" : 1 }
{ "_id" : "45", "num_posts" : 5 }

MongoCollection<Document> coll = MongoFactory.getCollection(db_name, db_collection);

List<Bson> aggregation = Arrays.asList(

        Aggregates.group("$idPagina", Accumulators.sum("count", 1)),

        Aggregates.sort(Sorts.descending("date")),

        Aggregates.project(Projections.fields(Projections.excludeId(), Projections.computed("idPagina", "$_id"), Projections.include("count"))));


Iterator<Document> sortedList = coll.aggregate(aggregation).iterator();

List<PostCount> result = new ArrayList<PostCount>();

现在如何进行分页?获得20页,而不是获得最后一页之后的其他20页? 例如:

docs  = coll.find().limit(postPerPage).sort(new BasicDBObject("date", -1));

日期排序不起作用。

0 个答案:

没有答案