Search code examples
javaspringmongodbspring-data-mongodb

Performing update using @Query via Spring Data MongoDB


i wanted to do a direct update to mongodb and setting someflag to either true or false for my use case. To be effecient i do not want to query all documents and set the someflag and save it back to db. i just want to directly update it on db just like when doing update on mongodb terminal.

Here is the sample document. NOTE: these documents can number from 1 ~ N so i need to handle efficiently big datas

{
  _id: 60db378d0abb980372f06fc1
  someid: 23cad24fc5d0290f7d5274f5
  somedata: some data of mine
  flag: false
}

Currently im doing an @Query method on my repository

@Query(value ="{someid: ?0}, {$set: {flag: false}}")
void updateFlag(String someid)

Using the above syntax, it doesnt work, i always get an exception message below;

Failed to instantiate void using constructor NO_CONSTRUCTOR with arguments

How do i perform a direct update effeciently without querying all those document and updating it back to db?


Solution

  • Use the BulkOperations class (https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/BulkOperations.html)

    Sample codes: Spring Data Mongodb Bulk Operation Example