0

I have an issue getting the sum of an array of objects, Document is mentioned below.

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

I need the below document

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

Sum of prices in totalItemsValue field.I need a solution in spring mongo data.I will be thankful.

0

1 Answer 1

1

There ae lot of ways, easiest way is given below. Spring data doesn't provide any operation for $addFields. So we do a Trick.

Autowire the mongoTemplate

@Autowired
private MongoTemplate mongoTemplate;

And the method is like

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

}

Working Mongo playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.