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

MongoDb how write aggregation query in java driver version 3.4

我无法在 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));

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

$group 聚合
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));