【问题标题】:How to count elements matching certain condition in array field and insert into projection with MongoDB java driver如何计算数组字段中匹配特定条件的元素并使用 MongoDB java 驱动程序插入到投影中
【发布时间】:2021-05-23 05:56:35
【问题描述】:

我从两个集合中进行了 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
                    )
                )
            )
        );

【问题讨论】:

    标签: java mongodb aggregation-framework projection


    【解决方案1】:

    好吧,你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-26
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      相关资源
      最近更新 更多