我需要以最“最佳实践”的方式将对象添加到嵌套在另一个对象内的数组中。
问题是我不想仅仅为了添加一个新对象而从数据库中拉出整个数组。必须有更好的方法来执行此操作,例如仅通过查询将新对象添加到数组中?
就目前而言,Im提起包含文章的Business对象,添加新文章,然后更新Business对象。
public interface BusinessRepository extends MongoRepository<Business, String> {
@Query(value="{ 'id' : ?0 }", fields="{ 'posts' : 1 }")
Business findOneIncludeOnlyPosts(String id, Pageable pageable);
}
我想要实现的是这样的:
@Query(value="{ SOME QUERY }")
void putPostInBusinessPosts(String id, Post post);
有可能还是我必须以更昂贵的方式来做?
使用:
您无法使用来实现MongoRepository
。您将不得不使用MongoTemplate
它。
我不认为它会更昂贵,但可能会更冗长。
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");
假设业务是集合的名称。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句