Philippe Gioseffi
Philippe Gioseffi

Reputation: 1658

Custom @Query annotated method for update query with spring data MongoRepository

I've read the question Custom method for update query with spring data MongoRepository and my result would be the very same that it is in que previously mentioned question, the only difference would be that I want to do it by using a @Query annotated method. Is it possible? If so, how?

I have a entity and I what to update all documents with a value if a determined criteria has been match.

My entity:

@Document("accrual")
public class Accrual extends AbstractEntity {

    @Serial
    private static final long serialVersionUID = 1175443967269096002L;

    @Indexed(unique = true)
    private Long numericUserId;
    @Indexed(unique = true)
    private Long orderIdentifier;
    private boolean error;

    // sets, gets, equals, hashCode and toString methods
}

I would like to update the boolean error in every document found by searching for them using a list of Longs matching orderIdentifier attribute.

If it was in a relational database I would have a method like:

@Query(value = "update accrual set error = 0 where order_identifier in :list", nativeQuery = true)
updateErrorByOrderIdentifier(@Param("list") List<Long> orderIdentifiers)

Upvotes: 1

Views: 1764

Answers (1)

artiomi
artiomi

Reputation: 625

You can try to use @Query annotation for filtering documents to be updated and @Update for providing actual update query.

@Query("{ 'orderIdentifier' : { '$in': ?0 } }")
@Update("{ '$set' : { 'error' : 'false' } }")
void updateAllByOrderIdentifier(List<Long> orderIdentifiers);

More details can be found here

Upvotes: 1

Related Questions