riccardo.cardin
riccardo.cardin

Reputation: 8353

Spring Data Mongo: upsert with various fields updated

I am searching for the right way to implement the upsert operation to a Mongo Collection using the API given by Spring Data.

In details, I have the following use case. The schema of the collection collection is something like the following:

{
  _id: "some_id",
  field1: "value1",
  field2: "value2",
  subdocument1: {
    // A subdocument with some fields
  },
  subdocument2: {
    // A subdocument with some other fields
  }
}

The fields field1 and field2 are always present, but subdocument1 and subdocument2 will be inserted in different moments: one during the first insertion, the second with a subsequent update.

I saw that MongoTemplate has and upsert method. Using this method I have to build my own the update operation.

Query query = Query.query(Criteria.where("_id").is("some_id"));
Update.update("_id", "some_id")
      .set("field1", "value1")
      .set("field2", "value2")
      .set("subdocument1", subdocumentObject);
mongoTemplate.upsert(query, update, Collection.class);

I cannot understand if it is what I am searching for and if there is a better approach.

Upvotes: 1

Views: 4649

Answers (1)

s7vr
s7vr

Reputation: 75914

I believe what you are looking for is $setOnInsert for subdocument1. So something like should work for you.

Query query = Query.query(Criteria.where("_id").is("some_id"));
Update update = Update.update("_id", "some_id")
                .set("field1", "value1")
                .set("field2", "value2")
                .set("subdocument2", subdocumentObject2)
                .setOnInsert("subdocument1", subdocumentObject1);

More here https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/

Upvotes: 5

Related Questions