【问题标题】:how to apply mongo db update operators as $inc in spring boot如何在 Spring Boot 中将 mongo db update 运算符应用为 $inc
【发布时间】:2020-09-07 00:27:00
【问题描述】:

我想做的只是使用 spring boot 和 mongodb 进行一个简单的查询,但我无法在线找到资源,更新查询以通过一个给定的 searchString 增加频率字段,或者如果找不到 searchString 则创建一个新文档。

@Query("{'searchString': ?0 } , {'$inc' : {'frequency':1}} ")
public void incFreq(String query);

【问题讨论】:

    标签: java mongodb spring-boot spring-data-jpa


    【解决方案1】:

    希望你使用 spring-data-mongodb。由于您没有提到 Document 类,我假设它是 Person.class

    首先你@Autowire服务实现中的MongoTemplate

    @Autowire
    MongoTemplate mongoTemplate;
    

    那么你可以做的是,你可以像下面这样调用查询,

    public void incFreq(String given_str){
        Query query=new Query(Criteria.where("searchString ").is("given_str"));
        Person person=mongoTemplate.find(query,Person.class);
    
        if(person!=null){
            Update update=new Update().inc("frequency",1)
            UpdateResult result=mongoTemplate.updateOne(query,update,Person.class);
            // bu using the result, you can see modifiedCount(),matchCount()
        }else{
            // insert query
        }
    }
    

    如果你打算使用 JPA 方法,那么

    public void incFreq(String given_str){
        Optional<Person> p=personRepository.findBySearchString(String given_str);
        if(p.isPresent()){
            p.get().setFrequency(p.get().getFrequency()+1);
            personRepository.save(p);
        }else{
            Person p=new Person();
            p.setName("some name");
            p.setFrequency(1);
            personRepository.save(p);
        }
    }
    

    参考Spring data mongodb

    【讨论】:

    • 我完全同意这两种解决方案,但是这些解决方案的问题是我会先访问数据库两次以查找然后进行更新,无论如何要使用 upsert 更新。
    • 哦,我以为你是初学者,可能是我浪费了我们俩的时间:'(。请参考$setOnInsertupsert
    【解决方案2】:
    @Autowired
       MongoTemplete mongotemplate;
    
    Update update = new Update();
    
        Query query = new Query();
        update.inc("listPrice",productItem.getListPrice());
    mongoTemplate.updateMulti(query,update,ProductCatalogItem.class);
    
        
    
    #"listPrice" : for which you wanna use $inc.
    #productItem : instance of your class
    

    【讨论】:

    • 请添加一些上下文以帮助该网站的未来访问者了解如何使用您的答案。这在How to Answer 中有介绍。
    猜你喜欢
    • 2016-09-01
    • 2019-04-18
    • 1970-01-01
    • 2019-01-06
    • 2020-12-04
    • 1970-01-01
    • 2017-03-25
    • 2016-04-19
    • 2016-01-02
    相关资源
    最近更新 更多