如何使用java获取mongoDB汇总的月份数据

时间:2015-05-15 11:48:02

标签: java mongodb aggregation-framework

这是我在db。

中的数据
^(?=select\(.*foo.*\)$)(?![^()]*\(\))[^()\n]*+(\((?>[^()\n]|(?1))*+\)[^()\n]*)++$

我希望每月提取总积分和借记的总和。 我想在java中做到这一点。

1 个答案:

答案 0 :(得分:1)

aggregation framework 与以下聚合管道(Mongo shell实施)一起使用:

db.ledger.aggregate([
    {
        "$unwind": "$Accounts"
    },
    {
        "$project": {
            "Total_Credits" : "$Accounts.Total_Credits",
            "Total_Debits" : "$Accounts.Total_Debits",
            "month_year" : {  "$substr": [ "$Accounts.Date", 3, -1 ] }
        }
    },
    {
        "$group": {
            "_id": "$month_year",
            "Total_Credits": { "$sum": "$Total_Credits" },
            "Total_Debits": { "$sum": "$Total_Debits" }
        }
    }
])

通过上面的示例,这将输出到控制台:

/* 0 */
{
    "result" : [ 
        {
            "_id" : "07-2015",
            "Total_Credits" : 1000,
            "Total_Debits" : 0
        }, 
        {
            "_id" : "05-2015",
            "Total_Credits" : 5000,
            "Total_Debits" : 0
        }
    ],
    "ok" : 1
}

使用Java,可以按如下方式实现:

import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

public class Aggregation {

    public static void main(String[] args) {

        DB db = MongoDb.getAccountsDb();
        DBCollection ledger = db.getCollection("ledger");

        //------------------------------------------------- aggregation framework

        DBObject unwind = new BasicDBObject("$unwind", "$Accounts");
        List<Object> substrList = Arrays.asList(new Object[]{"$Accounts.Date", 3, -1});
        DBObject monthProjection = new BasicDBObject("$substr", substrList);
        DBObject projectFields = new BasicDBObject("Total_Credits", "$Accounts.Total_Credits");
        projectFields.put("Total_Debits", "$Accounts.Total_Debits");
        projectFields.put("month_year", monthProjection);
        DBObject project = new BasicDBObject("$project", projectFields );

        DBObject groupFields = new BasicDBObject( "_id", "$month_year");
        groupFields.put("Total_Credits", new BasicDBObject( "$sum", "$Total_Credits"));
        groupFields.put("Total_Debits", new BasicDBObject( "$sum", "$Total_Debits"));
        DBObject group = new BasicDBObject("$group", groupFields);

        AggregationOutput output = ledger.aggregate( unwind, project, group );

        System.out.println("\n" + output);
    }

}