MongoDb如何在java驱动程序版本3.4中编写聚合查询

时间:2017-01-10 17:52:55

标签: java mongodb driver aggregation-framework mongodb-java

我没有办法在java中为此聚合查询的驱动程序版本3.4编写等效查询:

db.getCollection('MYTABLE').aggregate([ 
     {"$match": { "ID_STATUSMATRICULA": 1 } }, 
     {"$group": {
        "_id": null,
        "TOTAL" : { $sum: 1 },

        "MEDIA_APROVADOS": { 
            "$avg": {
                "$cond": [ { "$eq": [ "$ID_STATUSAPROVEITAMENTO", 1 ] }, "$NR_APROVEITAMENTO", 0, ]
            }
        },
        "MEDIA_REPROVADOS": { 
            "$avg": {
                "$cond": [ { "$eq": [ "$ID_STATUSAPROVEITAMENTO", 2 ] }, "$NR_APROVEITAMENTO", 0, ]
            }
        },
        "APROVADOS": { 
            "$sum": {
                "$cond": [ { "$eq": [ "$ID_STATUSAPROVEITAMENTO", 1 ] }, 1, 0, ]
            }
        },
        "REPROVADOS": { 
            "$sum": {
                "$cond": [ { "$eq": [ "$ID_STATUSAPROVEITAMENTO", 2 ] }, 1, 0, ]
            }
        },
        "PENDENTES": { 
            "$sum": {
                "$cond": [ { "$eq": [ "$ID_STATUSAPROVEITAMENTO", 0 ] }, 1, 0, ]
            }
        }
    }}
])

任何人都可以帮我这个吗?我找到了许多旧驱动程序2.2的样本,但3.4版本的文档很差。

已解决在Sagar Reddy回答之后,我可以在java中编写等效内容:

List pma = asList(new Document("$eq", asList("$ID_STATUSAPROVEITAMENTO", 1)), "$NR_APROVEITAMENTO", 0);
List pmr = asList(new Document("$eq", asList("$ID_STATUSAPROVEITAMENTO", 2)), "$NR_APROVEITAMENTO", 0);
List psa = asList(new Document("$eq", asList("$ID_STATUSAPROVEITAMENTO", 1)), 1, 0);
List psr = asList(new Document("$eq", asList("$ID_STATUSAPROVEITAMENTO", 2)), 1, 0);
List psp = asList(new Document("$eq", asList("$ID_STATUSAPROVEITAMENTO", 0)), 1, 0);

        Bson match = Aggregates.match(Filters.eq("ID_STATUSMATRICULA", 1));
        Bson group = Aggregates.group(null,
            sum("TOTAL", 1),
            avg("MEDIA_APROVADOS", computed("$cond", pma) ),
            avg("MEDIA_REPROVADOS", computed("$cond", pmr) ),
            sum("APROVADOS", computed("$cond", psa) ),
            sum("REPROVADOS", computed("$cond", psr) ),
            sum("PENDENTES", computed("$cond", psp) )
        );

        AggregateIterable<Document> cursor = mTable.aggregate(asList(match, group));

1 个答案:

答案 0 :(得分:4)

你可以尝试类似的东西。将其余字段添加到$group聚合,类似于MEDIA_APROVADOS

import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Projections.*;
import static java.util.Arrays.asList;

Bson match = Aggregates.match(Filters.eq("ID_STATUSMATRICULA", 1));
Bson group = group(null,
                avg("MEDIA_APROVADOS", 
                computed("$cond", 
                         asList(new Document("$eq", asList("$ID_STATUSAPROVEITAMENTO", 1)), 
                        "$NR_APROVEITAMENTO", 0))
                 )
           );
collection.aggregate(asList(match, group));