Spring Data Mongo:更新了各个领域的upsert [英] Spring Data Mongo: upsert with various fields updated

查看:97
本文介绍了Spring Data Mongo:更新了各个领域的upsert的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找使用Spring Data提供的API对Mongo集合实施 upsert 操作的正确方法.

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

详细地,我有以下用例.集合collection的架构类似于以下内容:

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
  }
}

字段field1field2始终存在,但是subdocument1subdocument2将在不同的时刻插入:一个在第一次插入时,第二个在随后的更新中.

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.

我看到MongoTemplate具有和

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.

推荐答案

我相信您正在寻找的是subdocument1$setOnInsert.所以类似的东西应该为您工作.

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);

更多信息 https://docs.mongodb.com/manual/参考/操作员/更新/setOnInsert/

这篇关于Spring Data Mongo:更新了各个领域的upsert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆