Search code examples
javaspringmongodbmongotemplate

UpdateMulti with aggregation,sort and limit


I am new in mongoTemplate, and I have to execute this query:

db.getCollection('collection').aggregate([
{$match:{param1:'1','gr.param2':'2',param3:'3'}},
{$sort:{date:-1}},
{$limit:1},
{$set:{'gr.pr1':'1'}}
])

I have tried to do this using this:

Query query = new Query(Criteria.where("param1").is("1").and("gr.param2")
                    .is("2")
                    .and("param3")
                    .is("3")
                    .with(new Sort(Sort.Direction.DESC, "date")).limit(1);
            
            Update update = new Update();
            update.set("gr.pr1","1");

            mongoTemplate.updateMulti(query, update, "collection");

This query is returning me N results, but I only want 1 (the last date)

Do you have any advice?


Solution

  • The problem seems to be related with updateMulti because that methods return the updated values, so you can try using findAndModify.

    Something like this:

    YourCollection yourObjectData = mongoTemplate.findAndModify(query, update, YourCollection.class);
    

    You can read the MongoDB Docs about returning data from db.collection.findAndModify.

    Note that default new value is false.

    In this tutorial you can check examples for updateMulti and findAndModify.