6

I need to add an object to an array nested inside an other object in the most "best practice way".

The problem is that I don´t want to pull up the whole array from the db just to add an new object. There must be a better way to do this like just adding the new object to the array by a query?

As for now Im pulling up a Business object with included posts, adding the new post and then updating the Business object.

public interface BusinessRepository extends MongoRepository<Business, String> {

    @Query(value="{ 'id' : ?0 }", fields="{ 'posts' : 1 }")
    Business findOneIncludeOnlyPosts(String id, Pageable pageable);
}

What I want to achieve is something like this:

@Query(value="{ SOME QUERY }")
void putPostInBusinessPosts(String id, Post post);

Is it possible or do I have to do it the more expensive way?

Using:

  • spring-boot 1.3.5
  • mongo-java-driver 3.2.2

1 Answer 1

11

You can't achieve it using a MongoRepository. You will have to use MongoTemplate for that.

I don't regard it to be more expensive, but more verbose maybe.

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

...

Update update = new Update();
update.addToSet("posts", post);
Criteria criteria = Criteria.where("_id").is(id);
template.updateFirst(Query.query(criteria), update, "business");

Assuming business is the name of the collection.

Sign up to request clarification or add additional context in comments.

4 Comments

Thx for your reply. Is there a way I could use both MongoRepository and MongoTemplate trough the BusinessRepository interface?
You can do it by having a custom repository implementation and injecting a MongoTemplate into it
BTW, you should use update.push instead of update.addToSet if you want to trigger $push.
how will mongotemplate know that to which collection it need to save ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.