0xRLA
0xRLA

Reputation: 3369

Add object to an array in java mongodb

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:

Upvotes: 6

Views: 9884

Answers (1)

Ori Dar
Ori Dar

Reputation: 19000

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.

Upvotes: 11

Related Questions