如何使用Spring Boot更新MongoDB集合中的子对象?

huangapple go评论85阅读模式
英文:

How to update a sub-object in a MongoDB collection with Spring Boot?

问题

我对Spring Data和StackOverflow都不太了解。

为了简单起见,在我的数据库中,我有一个'用户'集合,其中有一个带有'myApp'子对象和'param'子对象的用户文档。

目前我能够在用户文档中更新'param',但我想要做的是更新'myApp'中的'param'。

请问有什么好的做法吗?

以下是我的当前请求:

public ResponseEntity<?> setParam(String key, Param param){
    Query q = new Query(Criteria.where("_id").is(Auth.getUserId(key)));
    q.fields().include("myApp");
    Update u = Update.update("param", param).set("param", param);
    mongoTemplate.findAndModify(q, u, new FindAndModifyOptions().returnNew(true).upsert(false), User.class);
    return null;
}

提前谢谢!

英文:

I'm new to both Spring Data and StackOverflow.

To make it simple, in my database I have a 'user' collection in which I have a user document with a 'myApp' subobject and a 'param' subobject.

Currently I'm able to upsert 'param' in my user document except that what I want to do is to upsert to 'param' in 'myApp'.

What is the good practice please?

Here is my current request:

public ResponseEntity&lt;?&gt; setParam(String key, Param param){
        Query q = new Query(Criteria.where(&quot;_id&quot;).is(Auth.getUserId(key)));
        q.fields().include(&quot;myApp&quot;);
        Update u = Update.update(&quot;param&quot;, param).set(&quot;param&quot;, param);
        mongoTemplate.findAndModify(q, u, new FindAndModifyOptions().returnNew(true).upsert(false), User.class);
        return null;
}

Thank you in advance!

答案1

得分: 0

好的,我尝试了很多方法,最终找到了解决方案!
.update中只需使用"myApp.param",在.set中也只需使用"myApp.param"!
希望对其他人有帮助。

英文:

Ok I tried a lot of stuff and I finally found the solution!

It was enough in the .update to do "myApp.param" and in the .set to do "myApp.param" !

Hoping that it could be useful for others.

huangapple
  • 本文由 发表于 2020年10月23日 21:23:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64500875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定