Spring data mongo - 获取 mongo 中对象数组的总和

Spring data mongo - Get sum of array of object in mongo

我在获取对象数组的总和时遇到问题,下面提到了文档。

{
   "orderNumber":123,
   "items":[
      {
         "price":2
      },
      {
         "price":10
      }
   ]
}

我需要以下文件

{
   "orderNumber":123,
   "totalItemsValue":12,
   "items":[
      {
         "price":2
      },
      {
         "price":10
      }
   ]
}

价格总和在totalItemsValuefield.I需要解决方案在springmongodata.I将不胜感激。

方法有很多,下面给出最简单的方法。 Spring 数据没有为 $addFields 提供任何操作。所以我们做一个Trick.

自动装配 mongoTemplate

@Autowired
private MongoTemplate mongoTemplate;

方法就像

public List<Object> test() {
    Aggregation aggregation = Aggregation.newAggregation(
        a-> new Document("$addFields",
                new Document("totalItemsValue",
                    new Document("$reduce"
                        new Document()
                        .append("input","$items")
                        .append("initialValue",0)
                        .append("in",
                            new Document("$add",Arrays.asList("$$value",1))
                        )
                    )                   
            )
        )

    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();

}

工作Mongo playground