How to upsert nested value using Spring-Data for Mongodb

Viewed 265

I am trying to update the following JSON doc in mongodb so that a new document will be created if there is not one matching the "altKey", but if there is a document matching the altKey, any matching "records" will have their "domain" set and their "counts" incremented. I have a requirement that the JSON structure not change and that Spring-Data for mongodb is used.

{
    "altKey": "value"
    "records": {
        "randomName1" {
            "domain": "domainValue",
            "count": 3
        },
        "randomName2" {
            "domain": "domainValue2",
            "count": 5
        },

        ...

        "randomNameN" {
            "domain": "domainValueN",
            "count": 4
        }
    }
}

The relevent portion of the class I have been attempting to do the update with is:

@Autowired
private MongoTemplate mongoTemplate;

@Override
public void increment(Doc doc) {

    Query query = new Query().addCriteria(Criteria.where("altKey").is(doc.getAltKey());

    Update update = new Update();
    update.setOnInsert("altKey", doc.getAltKey());

    for (final Map.Entry<String, RecordData> entry :
           doc.getRecords().entrySet()) {

       String domainKey = format("records.{0}.domain", entry.getKey());
       String domainValue = entry.getValue().getDomain();
       update.set(domainKey, domainValue);

       String countKey = format("records.{0}.count", entry.getKey());
       Integer countValue = entry.getValue().getCount();
       update.inc(countKey, countValue);
    }

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

When I attempt to call the increment method the "altKey" field is successfully persisted, but none of the records persist and I am not sure of why that is. I believe the reason is my attempt to use mongo dot operation for the key when doing the set and inc update portions (ie "records.randomNameN.domain" or "records.randomNameN.count") but I haven't been able to find an alternate way to configure the Update object when I don't know until run time what the name of a particular record will be.

Anyone out there know how to set up the Update object to handle setting nested fields?

0 Answers
Related