0

I have the document (shown below) in mongodb database atlas with spring boot application. When I delete the document (seller) which is being referenced by the document shown below, the seller reference field is not deleted as well, thus rendering the seller field to refer to non-existing document.

_id: "Q8rWjRVCx4Avu3lvp0D6OuExac23SD"
editable: true
totalAmount: 0
amountPaid: 0
seller: DBRef(employees, BR1pKUGjZU8xdqIlaNvtO9VhqPqmi8, undefined)
_class: com.examle.Transaction

How can the referenced field (seller) be removed from the document by using spring boot operation(s). I have an idea that $unset operator can be used, however, this is a mongodb specific command while I want to carry out this action from my spring boot application. This is different compared to this question which addresses primitive data type, while my question is about references.

Hyacinth
  • 67
  • 2
  • 7

1 Answers1

0

Two possible solutions:

  1. Leave the document as is, even when the referenced seller document is deleted. Mongodb clears references which point to non-existing documents. With my experience, this happens when you perform action on the document, e.g., update or query action. Moreover, even if you query the database before the references are cleared, the return is empty, instead of null value.

  2. Second option is to use $unset operator as shown below.

    query.addCriteria(Criteria.where("seller").is(<seller id>));
    Update update = new Update();
    update.unset("seller");
    mongoTemplate.updateMulti(query, update, Transaction.class);
    
    

Note the use of seller id to represent the value of the reference in the query.

Hyacinth
  • 67
  • 2
  • 7