本文介绍了在Java中将包括$ cond的聚合转换为DBObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在MongoDB中构建了一个聚合
I have build an aggregation in MongoDB
{
"$project": {
"dt": "$dt",
"mc": "$mc",
"uplift": "$uplift",
"baseAvg": "$baseAvg",
"baseUp": { $add: [ "$uplift", "$baseAvg" ] },
"share": {
"$cond": [{
"$eq": ["$baseAvg", 0]
}, 0, {
"$divide": ["$uplift", "$baseAvg"]
}]
}
}
}
由于没有支持条件的ProjectOperation,因此我尝试使用DBObject构建查询.但是我被卡住了.
I'm trying to build the query by using DBObject since there is no ProjectOperation that supports condition. But I get stuck.
当我写这篇文章时:
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"
}]
}]
}
}
}
有人知道我应该怎么做吗?
Anybody knows what I should do?
推荐答案
您可以对Mongo Java 2.13版本使用以下聚合查询.我简化了一些操作.
You can use the below aggregation query for Mongo Java 2.13 version. I've simplified some operations.
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版本,您可以使用以下汇总.
For 3.x version you can use below aggregation.
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<>());
这篇关于在Java中将包括$ cond的聚合转换为DBObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!