mongodbspring-bootdbrefmongock

how should migrate my DBRef fields with mongock?


I have a problem with migrating an entity which has DBRef fields. If I change any field in this entity, my DBRefs are gone. What should I do?

    Query query = new Query();

    List<Criteria> criteriaList = new ArrayList<Criteria>();

    criteriaList.add(Criteria.where("created").exists(false));
    criteriaList.add(Criteria.where("updated").exists(false));

    query.addCriteria(new Criteria().orOperator(criteriaList.toArray(new Criteria[criteriaList.size()])));

    List<Asset> results = mongoTemplate.find(query, Asset.class);
    results.forEach(asset -> {
        asset.setCreated(asset.getCreatedBy().getCreated());

        mongoTemplate.save(asset);
    });

Solution

  • in summary, its problem is the MongoTemplate. mongoTemplate.save(...) creates a new entity and saves it to DB. As a consequence, if you want to change/update a field in your entity, you should use mongoTemplate.updateFirst(...). My solution is as the following.

    public void createAssetCreateOrUpdateDateIfNot(MongockTemplate mongockTemplate) {
        MongoTemplate mongoTemplate = mongockTemplate.getImpl();
    
        Query queryGetAssetsCreatedOrUpdatedIsNot = new Query();
    
        List<Criteria> criteriaList = new ArrayList<Criteria>();
        criteriaList.add(Criteria.where("created").exists(false));
        criteriaList.add(Criteria.where("updated").exists(false));
    
        queryGetAssetsCreatedOrUpdatedIsNot
                .addCriteria(new Criteria().orOperator(criteriaList.toArray(new Criteria[criteriaList.size()])));
    
        List<Asset> results = mongoTemplate.find(queryGetAssetsCreatedOrUpdatedIsNot, Asset.class);
    
        if (results.size() > 0) {
            for (Asset asset : results) {
                Date createdDate = (asset.getCreatedBy().getCreated() != null)
                        ? asset.getCreatedBy().getCreated()
                        : new Date();
                Date updateDate = (asset.getModifiedBy().getCreated() != null)
                        ? asset.getModifiedBy().getCreated()
                        : new Date();
    
                Query queryGetAssetViaId = new Query();
                queryGetAssetViaId.addCriteria(Criteria.where("id").is(asset.getId()));
    
                Update update = new Update()
                        .set("created", createdDate)
                        .set("updated", updateDate);
    
                mongoTemplate.updateFirst(queryGetAssetViaId, update, Asset.class);
            }
        }
    }