首页 文章

如何在mongoDB中使用morphia获取累加器结果?

提问于
浏览
0

我在Java中使用Morphia和MongoDB,我喜欢在聚合查询中获得许多记录:

AggregationPipeline pipCount = ds.createAggregation(MyTable.class)
            .match(query1)
            .match(query2)
            .unwind("transactions")
            .match(query3)
            .group("_id", grouping("_id"), grouping("count", new Accumulator("$sum", 1)));
Iterator<MyTable> result = pipCount.aggregate(MyTable.class);

我需要使用分组(“_ id”)删除重复的结果,然后计算结果,但找不到任何方法来读取总和值...任何想法?

样本数据:

{
    "_id": "00000222",
    "create_date": ISODate("2015-05-06T07:20:31.000+0000"),
    "update_date": ISODate("2015-05-06T07:20:31.000+0000"),
    "payment": 70.0,
    "fee": 0.0,
    "type": "RECURRING",
    "currency": "USD",
    "status": "OK",
    "transactions": [{
        "_id": "111111223",
        "amount": 1260.0,
        "fee_type": "VARIABLE_ADD",
        "fee_rate": 2.75,
        "status": "ERROR",
        "charges": [{
            "_id": "2222223344",
            "amount": 1000.0,
            "recurring": true,
            "firstTime": false,
            "oneTime": true,
        }, {
            "_id": "222222222233221",
            "amount": 70.0,
            "recurring": true,
            "firstTime": true,
            "oneTime": true,
        }]
    }],
    "users": {
        "_id": "33333333332212",
        "update_date": ISODate("2015-12-18T08:03:35.000+0000"),
        "user_id": "sdjfhsd@skjksdf.com",
        "first_name": "dsjfj",
        "last_name": "skdfjf",
    }
}

结果:1

1 回答

  • 1

    你可以尝试这样的事情 . 您不需要额外的分组 . 第一组将计算重复数,同时计算总和并计算计数并将响应映射到文档并读取计数 .

    import org.bson.Document; 
    
    AggregationPipeline pipCount = datastore.createAggregation(MyTable.class)
                .match(query1)
                .match(query2)
                .unwind("somethingID")
                .match(query3)
                .group("_id", grouping("count", new Accumulator("$sum", 1)))
                .project(Projection.projection("count"));
    
        Iterator<Document> result = pipCount.aggregate(Document.class);
    
        while (result.hasNext()) {
            Document document = result.next();
            Integer count = document.getInteger("count");
        }
    

相关问题