简体   繁体   中英

How to insert data in mongoDB

I want to write and read from a mongodb database. To create an entry, I use the following code:

private void updateMongoDb(TagEnum tag, BigDecimal minLen, BigDecimal maxLen,
                      List<BigDecimal> defaultLengths,
                      List<Double> lengthMultipliers, boolean useLengthMultipliers) {
    TagPreferences tagPreferences  = new TagDepositPreferences();
    tagPreferences.setProvider(tag);
    tagPreferences.setMinLen(minLen);
    tagPreferences.setMaxLen(maxLen);
    tagPreferences.setDefaultLengths(defaultLengths);
    tagPreferences.setLengthMultipliers(lengthMultipliers);
    tagPreferences.setUseLengthMultipliers(useLengthMultipliers);

    Query query = new Query();
    query.addCriteria(Criteria.where("tag").is(tag));
    query.addCriteria(Criteria.where("minLen").is(minLen));
    query.addCriteria(Criteria.where("maxLen").is(maxLen));
    query.addCriteria(Criteria.where("defaultLengths").is(defaultLengths));
    query.addCriteria(Criteria.where("lengthMultipliers").is(lengthMultipliers));
    query.addCriteria(Criteria.where("useLengthMultipliers").is(useLengthMultipliers));

    Update update = new Update();
    update.setOnInsert(tagPreferences.CREATED_AT, Instant.now());
    update.set(tagPreferences.LAST_MODIFIED_AT, Instant.now());
    update.set("tag", tagPreferences.getTag());
    update.set("minLen", tagPreferences.getMinLen());
    update.set("maxLen", tagPreferences.getMaxLen());
    update.set("defaultLengths", tagPreferences.getDefaultLengths());
    update.set("useLengthMultipliers", tagPreferences.isUseLengthMultipliers());
    update.set("lengthMultipliers", tagPreferences.getLengthMultipliers());

    mongoTemplate.upsert(query, update, TagPreferences.class);
}

and to read from it, I have a repository class with a method

TagPreferences findAllByTag(TagEnum tag);

And I do:

 TagPreferences tagPreferences = tagPreferencesRepository.findAllByTag(TagEnum tag);

The problem is that while I execute updateMongoDb only once, when I execute the findAllByTag() method I always get three results with the same values, instead of one. It would be really helpful if you could please explain the root cause behind that, and suggest corrections.

@Joe gave the solution in the commenting section. The issue was that after repetitive runs of the program, the mongo database had been filled with unrelated entries. This is resolved by creating a

void deleteAllByTag(TagEnum tagEnum);

method on the TagPreferencesRepository and calling it from inside the updateMongoDb() method, on the top.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM