MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

Transformez l'agrégation, y compris $cond en DBObject en Java

Vous pouvez utiliser la requête d'agrégation ci-dessous pour la version Mongo Java 2.13. J'ai simplifié certaines opérations.

 List<DBObject> aggregates = Arrays.asList(new BasicDBObject("$project", new BasicDBObject("dt", "$dt").
            append("mc", "$mc").
            append("uplift", "$uplift").
            append("baseAvg", "$baseAvg").
            append("baseUp", new BasicDBObject("$add", Arrays.<Object>asList("$uplift", "$baseAvg"))).
            append("share", new BasicDBObject("$cond", Arrays.<Object>asList(new BasicDBObject("$eq", Arrays.<Object>asList("$baseAvg", 0)),
                    0, new BasicDBObject("$divide",  Arrays.<Object>asList("$uplift", "$baseAvg")))))));

Pour la version 3.x, vous pouvez utiliser l'agrégation ci-dessous.

 MongoClient mongoClient = new MongoClient();
 MongoDatabase db = mongoClient.getDatabase("db");
 MongoCollection<Document> collection = db.getCollection("collection");
 Bson aggregates = Aggregates.project(Projections.fields(Projections.include("dt", "mc", "uplift","baseAvg"),
               new Document("baseUp", new Document("$add", Arrays.<Object>asList("$uplift", "$baseAvg"))),
               new Document("share", new Document("$cond", Arrays.<Object>asList(new Document("$eq", Arrays.<Object>asList("$baseAvg", 0)),
                                        0, new Document("$divide",  Arrays.<Object>asList("$uplift", "$baseAvg")))))));
 List<Document> results = collection.aggregate(Arrays.asList(aggregates)).into(new ArrayList<>());