How to run a custom mongodb query in spring-boot

Prakash Pandey picture Prakash Pandey · Jun 5, 2017 · Viewed 18.5k times · Source

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?

Answer

harshavmb picture harshavmb · Jun 5, 2017

Well, I should admit I couldn't find a way to update the document using custom mongo query. But, found a way of doing it using java8 streams.

 userActivityRepository.save(userActivityRepository.findAllDocuments(1234, 0)
.stream()
.peek((user) -> user.setStatus(user.getStatus() + 1))
.collect(Collectors.toList()));

The above statement uses userActivityRepository.findAllDocuments for fetching the records with a criteria then uses OOTB MongoRepository save(Iterable<S> entites) method to update the documents.

In place of $inc have incremented the status field.

This may not be what you are expecting, but just a possible solution if you wish to implement.

Hope this helps!