如何编写标准查询Mongodb组聚合

时间:2017-02-13 12:54:27

标签: spring mongodb hibernate

Mongodb $group

db.careLogBean.aggregate([{
    $unwind: "$comments"
}, {
    $sort: {
        "comments.time": -1
    }
}, {
    $group: {
        _id: "$_id",
        careGiverId: {
            $first: "$careGiverId"
        },
        careGiverName: {
            $first: "$careGiverName"
        },
        comments: {
            $push: "$comments"
        }
    }
}])

在mongodb $group聚合事物......如何用java标准编写                    查询语言......

1 个答案:

答案 0 :(得分:1)

您可以尝试以下聚合。

import static org.springframework.data.domain.Sort.Direction.DESC;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

Aggregation aggregation = newAggregation(
       unwind("comments"),
       sort(DESC, "comments.time"), 
       group("_id")
          .first("careGiverId").as("careGiverId")
          .first("careGiverName").as("careGiverName")
          .push("comments").as("comments"));

List<BasicDBObject> dbObjects = mongoOperations.aggregate(aggregation , collection_name, BasicDBObject.class).getMappedResults();

您可以根据您的设置调整最后一个语句。