如何在Spring数据Mongodb中使用ArrayOperation的Size类进行聚合?

时间:2018-07-17 12:43:47

标签: mongodb aggregation-framework spring-data-mongodb

{
"_id" : ObjectId("5b4d975be2194da53a85e69f"),
"ISBN" : 2,
"book_title" : "ZERO TO ONE",
"author_name" : "Peter Theil",
"publisher" : "Penguin",
"status" : "ISSUED",
"issued" : [
    {
        "member_name" : "suresh",
        "member_id" : 101,
        "from_date" : "1/01/2018",
        "to_date" : "15/02/2018"
    },
    {
        "member_name" : "Jay",
        "member_id" : 103,
        "from_date" : "16/02/2018",
        "to_date" : "30/03/2018"
    }
]}

这是我的Mongodb文档格式。我想做的是每个文档的Count数组长度。因此,对于此文档,我的输出将为Count:2。我想用spring数据mongodb实现这一点。我参考了那里的文档,发现在ArrayOperators类的链接中有一个Size类。

Spring data mongodb Documentaion

但是我不知道Use Size类?

Mongodb终端查询是:

    db.library.aggregate([{$project:{count:{$size:"$issued"},"book_title":1,"_id":0}])

1 个答案:

答案 0 :(得分:0)

您可以尝试以下汇总。

使用ArrayOperators

ProjectionOperation project = Aggregation.
            project("book_title").  
            andExclude("_id").
            and(ArrayOperators.arrayOf("issued").length()).as("count");

使用尺寸助手方法

ProjectionOperation project = Aggregation.
            project("book_title").
            andExclude("_id").
            and("issued").size().as("count");

聚合汇总

Aggregation aggregation = Aggregation.newAggregation(project);
List<Document> results = mongoTemplate.aggregate(aggregation, "library", Document.class).getMappedResults();