I have this documents (cut out for simplification):
{"Type" : "Book", "BookId" : 920, "Cost": 2000, "TypeId": 1, "_id" : "Book_1_920"},
{"Type" : "Book", "BookId" : 921, "Cost" : 1800, "TypeId": 1, "_id" : "Book_1_921"},
{"Type" : "Rate", "BookId" : 920, "RateId":1, "Rating": 3, "TypeId": 1, "_id" : "Rate_1_920_1"},
{"Type" : "Rate", "BookId" : 920, "RateId":2, "Rating": 5, "TypeId": 1, "_id" : "Rate_1_920_2"}
I want to create an aggregate by TypeId so the final output should be something like this:
{TypeId: 1, sumRatings: 8, costofBooksTotal: 3800, totalBooksCount: 2}
I am doing the following but first the numbers are wait out of line and secondly, I can’t seem to get TypeId (it returns null). It works fine if the queries are separated but I am hoping to do a Join:
Query query = QueryBuilder.select(
SelectResult.expression(Function.sum(Expression.property("Cost").from("books"))),
SelectResult.expression(Function.sum(Expression.property("Rating").from("ratings"))),
SelectResult.expression(Expression.property("TypeId").from("books"))
)
.from(DataSource.database(this.database).as("books"))
.join(Join.join(DataSource.database(this.database).as("ratings"))
.on(Expression.property("TypeId").from("books").equalTo(Expression.property("TypeId").from("ratings"))))
.where(Expression.property("Type").from("books").equalTo(Expression.string("Book"))
.and(Expression.property("Type").from("ratings").equalTo(Expression.string("Rating")))
).groupBy(Expression.property("TypeId").from("books"));
in my output, I get TypeId as null and the sum values way out of line.