Java MongoDB投影

问题描述

我指的是mongodb官方页面的投影,在这里我遇到以下示例,其中过滤了子文档中的数组元素: https://docs.mongodb.com/manual/reference/operator/aggregation/filter/#exp._S_filter

db.sales.aggregate([
   {
      $project: {
         items: {
            $filter: {
               input: "$items",as: "item",cond: { $gte: [ "$$item.price",100 ] }
            }
         }
      }
   }
])

我正在尝试用Java实现此功能,但未正确执行,并且未过滤子文档数组中的元素。

输入集合:

{
   _id: 0,items: [
     { item_id: 43,quantity: 2,price: 10 },{ item_id: 2,quantity: 1,price: 240 }
   ]
}
{
   _id: 1,items: [
     { item_id: 23,quantity: 3,price: 110 },{ item_id: 103,quantity: 4,price: 5 },{ item_id: 38,price: 300 }
   ]
}
{
    _id: 2,items: [
       { item_id: 4,price: 23 }
    ]
}

预期的输出集合:

{
   "_id" : 0,"items" : [
      { "item_id" : 2,"quantity" : 1,"price" : 240 }
   ]
}
{
   "_id" : 1,"items" : [
      { "item_id" : 23,"quantity" : 3,"price" : 110 },{ "item_id" : 38,"price" : 300 }
   ]
}
{ "_id" : 2,"items" : [ ] }

在Java(mongo驱动程序3.9.1)中,这就是我正在做的事情:

Bson priceFilter = Filters.gte("items.price",100);
mongoCollection.aggregate(
  Aggregates.project(Projections.fields(priceFilter))
);

如何在需要根据某些条件从子文档数组中滤除元素的子文档数组中使用聚合函数进行投影?

解决方法

MongoDB Java驱动程序3.9.1 中, collection.aggregate() java.util.List 作为参数。因此,您需要使用以下代码替换Java代码。

mongoCollection.aggregate(
                  Arrays.asList(
                               Aggregates.project(Projections.computed("items",new Document().append("$filter",new Document().append("input","$items").append("as","item").append("cond",new Document().append("$gte",Arrays.asList("$$item.price",100))))))
                              )
                   );