Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • spring-boot 1.3.5
  • mongo-java-driver 3.2.2
like image 989
rilar Avatar asked Jul 08 '16 08:07

rilar


1 Answers

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.

like image 83
Ori Dar Avatar answered Oct 17 '22 18:10

Ori Dar