Daten in mongo:Wie schreibe ich im Frühjahr Mongo-Aggregation reduzieren Abfrage?
db.test2.aggregate([
{
"$project" : {
"contents" : 1,
"comments" : {
"$filter" : {
"input" : "$comments",
"as" : "item",
"cond" : {"$gt" : ['$$item.score', 2]}
},
},
"comments2" : {
"$filter" : {
"input" : "$comments2",
"as" : "item",
"cond" : {"$gt" : ["$$item.score", 5]}
}
}
}
},
{
"$project" : {
"content" : 1,
"commentsTotal" : {
"$reduce" : {
"input" : "$comments",
"initialValue" : 0,
"in" : {"$add" : ["$$value", "$$this.score"]}
}
},
"comments2Total" : {
"$reduce" : {
"input" : "$comments2",
"initialValue" : 0,
"in" : {"$add" : ["$$value", "$$this.score"]}
}
}
}
},
{$skip : 0},
{$limit: 3}
]);
So können Sie sehen, dies macht folgendes: 1, filtern Sie die Kommentare und Kommentare2 die gt Tor gegangen 5. 2, zählen insgesamt der socre in Kommentar-Array.
und ich schreibe die Aggregation Abfrage im Frühjahr wie folgt aus:
AggregationExpression reduce = ArithmeticOperators.Add.valueOf("$$value").add("$$this.socre");
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.project().andExclude("_id")
.andInclude("content")
.and("comments").filter("item", ComparisonOperators.Gt.valueOf("item.score").greaterThanValue(3)).as("comments")
.and("comments2").filter("item", ComparisonOperators.Gt.valueOf("item.score").greaterThanValue(3)).as("comments2"),
Aggregation.project("comments", "comments2")
.and(ArrayOperators.Reduce.arrayOf("comments").withInitialValue("0").reduce(reduce)).as("commentsTotal")
);
wenn ich laufe wie oben, wird es wirft Ausnahme:
java.lang.IllegalArgumentException: Ungültige Referenz '$$ Wert' !
Sieht aus wie zwei Projektphase dieses Verhalten verursacht. Wir können dieses Problem leicht umgehen, wenn Sie nur die Anzahl als endgültige Ausgabe benötigen, wie in Ihrer Shell-Abfrage angezeigt. – Veeram
Wie kann ich jetzt tun? –