描述
直接写mongo的sql很简单。但是如果遇到聚合操作就不一定了。
我需要将聚合的两个字段相加。
本来springboot支持直接写mongo命令的。后来不知道,为什么不能用了。
解决办法
MongoCollection<Document> collection = database.getCollection("myCollection");
AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
new Document("$unwind", "$views"),
new Document("$match", new Document("views.isActive", true)),
new Document("$sort", new Document("views.date", 1)),
new Document("$limit", 200),
new Document("$project", new Document("_id", 0)
.append("url", "$views.url")
.append("date", "$views.date"))
));
// Print for demo
for (Document dbObject : output)
{
System.out.println(dbObject);
}
这种形式跟 mongo的语法最接近了。
db.UserInfo.aggregate([
{
$match:{statisticsTime:{$gt:1580604627000,$lt:4110679570000},
userCode:"ID89777666"
}
}
,
{
$group:{
_id:"$childernode",
Duration:{$sum:{$add:["$fireDuration","$outDuration"]}},
Times:{$sum:{$add:["$fireTimes","$outTimes"]}}
}
}]).skip(3).limit(5)
遇到问题
$project 与 $group 有冲突
你只能用一个。
总结
没了