我在MongoDB中构建了一个聚合
{
"$project": {
"dt": "$dt",
"mc": "$mc",
"uplift": "$uplift",
"baseAvg": "$baseAvg",
"baseUp": { $add: [ "$uplift", "$baseAvg" ] },
"share": {
"$cond": [{
"$eq": ["$baseAvg", 0]
}, 0, {
"$divide": ["$uplift", "$baseAvg"]
}]
}
}
}
我尝试使用DBObject构建查询,因为没有支持条件的ProjectOperation。但是我被卡住了。
当我写这篇文章时:
ArrayList condArray = new ArrayList();
condArray.add(new BasicDBObject("$eq", new DBObject[] { new BasicDBObject("$baseAvg", 0) }));
condArray.add(0);
condArray.add(new BasicDBObject("$divide", new DBObject[] { new BasicDBObject("$uplift", "$baseAvg") }));
DBObject doc = new BasicDBObject("$baseAvg", 0);
DBObject operation = new BasicDBObject("$project",
new BasicDBObject(groupItem, "$_id." + groupItem)
.append("mc", "$mc")
.append("uplift", "$uplift")
.append("baseAvg", "$baseAvg")
.append("sumBaseUp", new BasicDBObject("$add", new DBObject[] {"$uplift", "$baseAvg"}))
.append("share", new BasicDBObject("$cond", condArray)));
我得到了这个结果:
{
"$project": {
"dt": "$dt",
"mc": "$mc",
"uplift": "$uplift",
"baseAvg": "$baseAvg",
"sumBaseUp": {
"$add": [{
"$uplift": "$baseAvg"
}]
},
"share": {
"$cond": [{
"$eq": [{
"$baseAvg": 0
}]
}, 0, {
"$divide": [{
"$uplift": "$baseAvg"
}]
}]
}
}
}
有人知道我应该做什么吗?
答案 0 :(得分:2)
您可以对Mongo Java 2.13版本使用以下聚合查询。我已经简化了一些操作。
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")))))));
对于3.x版本,您可以使用以下聚合。
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<>());