All I want to do is a simple query using spring boot and mongodb but I can't find resources online, update query to increment frequency field by one given searchString or create a new document if searchString is not found.
@Query("{'searchString': ?0 } , {'$inc' : {'frequency':1}} ")
public void incFreq(String query);
Hope you use spring-data-mongodb . Since you haven't mentioned about the Document class, I assume it as Person.class
First you @Autowire
the MongoTemplate in the service implementation.
@Autowire
MongoTemplate mongoTemplate;
Then what you can do is, you can call a query like following,
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
}
}
If you going to use JPA methods, then
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);
}
}
Refer Spring data mongodb
@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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.