How to run a custom mongodb query in spring-boot

Viewed 21158

I have a spring-boot application and I am trying to run this below query using it.

db.userActivity.findAndModify(
{ 
   query: { 'appId' : 1234, 'status' : 0},
   update: { $inc: { 'status': 1 } } 
});

I did try something like this but it didn't work

public interface UserActivityRepository extends MongoRepository<UserActivity, String> {

    /**
     * Find all documents in the database
     * @param appId
     * @param status
     * @return
     */
    @Query("{ 'appId' : ?0, 'status' : ?1}")
    public List<UserActivity> findAllDocuments(long appId, int status);

    /**
     * Find all documents by appId whose state is unread
     * and marked them read after reading
     * @param appId
     * @return 
     */
    @Query("db.userActivity.findAndModify({ query: { 'appId' : ?0, 'status' : ?1}, update: { $inc: { 'status': 1 } } })")
    public List<UserActivity> findAndUpdateAllUnreadDocuments(long appId, int status);
}

Could you please tell what I am doing wrong?

3 Answers

Your Types for the MongoRepository are <UserActivity, String>. I assume String should be your ID and i only see long and int passed as Parameters in your custom queries.

From the Docs

@NoRepositoryBean
public interface ReactiveMongoRepository<T, ID> extends ReactiveSortingRepository<T, ID>, ReactiveQueryByExampleExecutor<T>
  • @see CrudRepository
  • @param the domain type the repository manages
  • @param the type of the id of the entity the repository manages
Related