How to update particular field in mongo db by using MongoRepository Interface?

前端 未结 2 1908
旧时难觅i
旧时难觅i 2021-01-13 02:56

How to update a particular field in mongo db collection by using MongoRepository Interface in spring?

2条回答
  •  爱一瞬间的悲伤
    2021-01-13 03:33

    As of today, you can't update the document using MongoRepository using one query. If you really want to update a particular field using MongoRepository then following is the steps:

    1. Fetch the document that you want to update
    2. Set the new value to a particular field and save that document.

    Example:

    MyDocument myDocumentToUpdate = myDocumentRepository.findById(documentId); // fetching a document that you want to update the field
    myDocumentToUpdate.setMyField(myNewValue); // setting the new value to the field myField
    myDocumentRepository.save(myDocumentToUpdate); // saving (It basically updates the document) the updated document
    

提交回复
热议问题