Spring Data Mongo: upsert with various fields updated

爱⌒轻易说出口 提交于 2019-12-04 05:39:28

问题


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.


回答1:


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/



来源:https://stackoverflow.com/questions/43248469/spring-data-mongo-upsert-with-various-fields-updated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!