MongoDB and Spring Boot – Best way to update a Document?

We Are Going To Discuss About MongoDB and Spring Boot – Best way to update a Document?. So lets Start this Java Article.

MongoDB and Spring Boot – Best way to update a Document?

  1. MongoDB and Spring Boot – Best way to update a Document?

    If you don't send the id with your request, the data will be
    inserted.
    If you send the existing id with your request, the data will be
    updated.

  2. MongoDB and Spring Boot – Best way to update a Document?

    If you don't send the id with your request, the data will be
    inserted.
    If you send the existing id with your request, the data will be
    updated.

Solution 1

Note : The following code is not tested, but it gives you an idea well.
There are two scenarios.

  1. If you don’t send the id with your request, the data will be
    inserted.
  2. If you send the existing id with your request, the data will be
    updated.

Annotate @Id private ObjectId _id; in your entity class

Controller

@RestController
@RequestMapping("YOUR_URL")
public class RoundController{

    @PostMapping("YOUR_URL")
    public ResponseEntity<Round> update(@Valid @RequestBody Round updateRound, BindingResult result){

        //Bindning Error handle
         if (bindingResult.hasErrors()) {
            List<String> errors = new ArrayList<>();
            for (ObjectError res : bindingResult.getFieldErrors()) {
                errors.add(res.getDefaultMessage());
            }

            throw new RuntimeError(errors.toString());
        }
        return new ResponseEntity<>(roundService.save(updateRound), HttpStatus.OK);
    }
}

Repository

interface RoundRepository extends MongoRepository<Round, ObjectId> {
}

Service

interface RoundService {
    Round save(Round round);
}

Service Implementation

@Service
public RoundServiceImpl implements RoundService{
    @Autowired
    RoundRepository repository;

    @Override
    public Round save(Round round){
        repository.save(round);
    }
}

You don’t need to actually perform a special query. But if you need to do some logic.

@Override
public Round save(Round round){

    if(round.get_id()!=null){
        //update logic
    }else {
        // insert logic
    }

    repository.save(round);
}

Original Author Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment