我實際上需要在 mongoDb 中使用聚合。我已經使用以下查詢加入兩個集合,然后通過一些過濾器提取答案。該查詢在 mongodb 終端中運行良好。
但是我需要在springboot中使用aggreagte函式在springboot中使用這個查詢。我查看了以下檔案,這非常有用。但是由于查詢很大。這就是為什么我無法以正確的方式撰寫它。
https://www.baeldung.com/spring-data-mongodb-projections-aggregations
db.coll1.aggregate([
{
"$unionWith": {"coll": "coll2"}
},
{
"$group": {
"_id": {
"stationId": "$stationId",
"gapStartTimeStamp": {
"$arrayElemAt": [
{
$split: [
"$gapStartTimeStamp",
"T",
]
},
1
]
},
"gapEndTimeStamp": {
"$arrayElemAt": [
{
$split: [
"$gapEndTimeStamp",
"T",
]
},
1
]
}
},
"count": {
"$sum": 1
}
}
},
{
"$match": {
"$expr": {
"$gt": [
"$count",
1
]
}
}
}])
你能幫我使用 aggreagte 函式并轉換這個查詢,以便我可以在 springboot 中使用它。
uj5u.com熱心網友回復:
看起來像試圖做一個計數(*),按 trunc(gapStartTimeStamp),trunc(gapEndTimeStamp)分組,其中 count > 1
如果是這種情況:您的查詢略有不同,使用 spring-data-mongodb 3.1.8 測驗
UnionWithOperation unionWith = UnionWithOperation.unionWith("coll2");
ProjectionOperation convertStartDateOp = Aggregation.project("stationId", "gapStartTimeStamp", "gapEndTimeStamp")
.and(StringOperators.Substr.valueOf("gapStartTimeStamp").substring(0, 10))
.as("gapStartDate")
.and(StringOperators.Substr.valueOf("gapEndTimeStamp").substring(0, 10))
.as("gapEndDate");
GroupOperation countOp = Aggregation.group("stationId", "gapStartDate", "gapEndDate").count().as("count");
MatchOperation matchOp = Aggregation.match(Criteria.where("count").gt(1));
AggregationResults<Document> aggregate = mongoOps.aggregate(
Aggregation.newAggregation(
unionWith,convertStartDateOp,countOp, matchOp
),
YourColl1.class, Document.class);
List<Document> mappedResults = aggregate.getMappedResults();
生成此查詢:
db.coll1.aggregate(
[
{"$unionWith": {"coll": "coll2"}},
{"$project":
{
"stationId": 1,
"gapStartTimeStamp": 1,
"gapEndTimeStamp": 1,
"gapStartDate": {"$substr": ["$gapStartTimeStamp", 0, 10]},
"gapEndDate": {"$substr": ["$gapEndTimeStamp", 0, 10]}
}
},
{"$group": {
"_id": {
"stationId": "$stationId",
"gapStartDate": "$gapStartDate",
"gapEndDate": "$gapEndDate"
},
"count": {"$sum": 1}
}
},
{"$match": {"count": {"$gt": 1}}}
]
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414135.html
標籤:
下一篇:使用貓鼬進行嵌套分組
