[英]How to count elements matching certain condition in array field and insert into projection with MongoDB java driver
I have made Aggregations.lookup from two collections, that returned list of stores, each having field of array of displayed products, with each product having its price.我从两个 collections 进行了 Aggregations.lookup,返回了商店列表,每个商店都有显示产品数组的字段,每个产品都有价格。 The task is to receive projection, showing for each shop:任务是接收投影,显示每个商店:
The problem is I don't understand exactly how to fulfill the fourth task, cause i don't quite understand the syntax of projections.computed.问题是我不完全了解如何完成第四个任务,因为我不太了解 projections.computed 的语法。 Here's code这是代码
AggregateIterable<Document> it = storesCollection.aggregate(Arrays.asList(
lookup("Products", "products", "name", "products_displayed")
, project(fields(
include("name")
, excludeId()
, computed("total", computed("$size", "$products_displayed")) //total
, computed("avgprice", computed("$avg", "$products_displayed.price")) //avg
, computed("maxprice", computed("$max", "$products_displayed.price")) //max
, computed("minprice", computed("$min", "$products_displayed.price")) //min
, computed("total lt 10", computed("$size", )) // this is the problem: count total amount of products with prices less than 10
)
)
)
);
Well, here's how you can do this:好吧,您可以这样做:
AggregateIterable<Document> it = storesCollection.aggregate(
Arrays.asList(
lookup("Products", "products", "name", "products_displayed")
, project(fields(
excludeId()
, include("name")
, computed("total", computed("$size", "$products_displayed"))
, computed("avgprice", computed("$avg", "$products_displayed.price"))
, computed("maxprice", computed("$max", "$products_displayed.price"))
, computed("minprice", computed("$min", "$products_displayed.price"))
, computed("total_lt_100", computed("$size",
eq("$filter", and(
eq("input", "$products_displayed"),
eq("as", "item"),
lt("cond", Arrays.asList("$$item.price", 100))
)
)))
)
)
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.