最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Why is there no option to upsert with Spring-data-mongodb annotations? - Stack Overflow

programmeradmin3浏览0评论

Using mongoTemplate in spring-data-mongodb (3.4.18), I can do

mongoTemplate
    .update(MyClass.class)
    .matching(query(where(...)))
    .apply(new Update()
        .set(...)
        .setOnInsert(...)
    .upsert();   // this upsert() seems impossible with annotations

The linked answer has another variant, using FindAndModifyOptions:

mongoTemplate.update(Foo.class)
  .matching(query)
  .apply(update)
  .withOptions(FindAndModifyOptions.options().upsert(true))
  .findAndModifyValue()

Also using mongodb, this upsert seems to be defined as upsert:true like:

db.employee.findAndModify({query:{name:"Ram"}, 
                            update:{$set:{department:'Development'}, $setOnInsert: { Gender: 'Female' } },
                            upsert:true})

Yet when trying to define this using annotations, I cannot find a way to indicate I want to do upsert:

public interface MyClassRepository extends MongoRepository<MyClass, String> {

    @Query("{name:'Ram'}")
    @Update("{$set:{department:'Development'}, $setOnInsert: { Gender: 'Female' } }")
    void upsertDepartmentAndGender(String department, String gender);

}

And this does not seem to insert anything if the query does not find any document.

I have tried @Update("{$set:{department:'Development'}, $setOnInsert: { Gender: 'Female' } , upsert: true}") without success.

发布评论

评论列表(0)

  1. 暂无评论