繁体   English   中英

如何使用 MongoDB java 驱动程序计算数组字段中匹配特定条件的元素并插入投影

[英]How to count elements matching certain condition in array field and insert into projection with MongoDB java driver

我从两个 collections 进行了 Aggregations.lookup,返回了商店列表,每个商店都有显示产品数组的字段,每个产品都有价格。 任务是接收投影,显示每个商店:

  1. 产品总量
  2. 平均产品价格
  3. 最贵和最便宜产品的价格
  4. 以及价格低于 10 的产品数量

问题是我不完全了解如何完成第四个任务,因为我不太了解 projections.computed 的语法。 这是代码

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
                    )
                )
            )
        );

好吧,您可以这样做:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM