database - MongoTemplate Criteria Criteria for Query 以更新对象数组中的元素
问题描述
我正在尝试为特定答案推送评论,我尝试了各种方法,但评论总是被添加到父问题中,而不是针对该问题中的答案。
我的数据库层次结构:
- 问题1
- 评论1
- 评论2
- 答案1
- CommentForAnswer1
- 答案2
我的模型类
问题.java
@Document(collection = "QUESTION")
public class QUESTION {
@Id
private String questionId;
private String questionHeader;
private String questionBody;
private String byUser; //username
private Instant postedAt;
private int upVotes;
private int downVotes;
private List<ANSWER> answerObj;
private List<COMMENT> commentObj;
答案.java
public class ANSWER {
private String answerId;
private String answerBody;
private String byUser; //username
private Instant postedAt;
private int upVotes;
private int downVotes;
private List<COMMENT> commentObj;
COMMENT.java
public class COMMENT {
private String commentId;
private String commentBody;
private String byUser; //username
private Instant postedAt;
private int upVotes;
private int downVotes;
控制器
@PostMapping(value = "posts/{questionId}/add")
public ResponseEntity<?> postComment(@PathVariable String questionId,
@RequestParam(value = "answerId", defaultValue = "") String answerId,
@RequestBody PostCommentRequest postCommentRequest,
Authentication authentication) {
String username = authentication.getName();
PostCommentResponse postCommentResponse = postService.postAComment(postCommentRequest, username, questionId, answerId);
return ResponseEntity.ok().body(postCommentResponse.getMessage());
}
存储库
update.push("commentObj", comment);
try {
query.addCriteria(answerId.isEmpty() ?
(new Criteria("questionId").is(questionId)) :
(new Criteria("answerObj.answerId").is(answerId).andOperator(Criteria.where("questionId").is(questionId))));
mongoTemplate.updateFirst(query, update, QUESTION.class, QUESTION_COLLECTION);
return new PostCommentResponse("Successfully updated!", comment);
} catch (Exception e) {
return new PostCommentResponse("Failed to update, Reason: " + e.toString(), null);
}
有人可以帮我找出可以将对象推送到另一个对象数组中的查询条件。
编辑:MongoDB 4.0 版(最新)
解决方案
这是我对这种情况的建议:
public Mono<ProjectChild> UpdateCritTemplChild(
String id, String idch, String ownername) {
Query query = new Query();
query.addCriteria(Criteria.where("_id")
.is(id));
query.addCriteria(Criteria.where("tasks._id")
.is(idch));
Update update = new Update();
update.set("tasks.$.ownername", ownername);
return template
// findAndModify:
// Find/modify/get the "new object" from a single operation.
.findAndModify(
query, update,
new FindAndModifyOptions().returnNew(true), ProjectChild.class
)
;
}
推荐阅读
- html - Conditional pattern to be used along with required Angular7/8
- hadoop - 清理本地 tmp 后纱线未启动
- julia - 如何在不关闭 Julia 环境的情况下清理 Plots (GR)
- javascript - 我需要通过 url 下载 PDF
- yocto - bitbake 构建找不到稀疏的
- python - 按类别组合列表并为每个列表创建带有描述的新列
- angular - Angular 6 app 组件和子组件执行
- sql - 在 MS-ACCESS 的 1 个概览中显示来自不同查询的结果
- c - 覆盖变量实际上是如何工作的?
- node.js - 在 through 子句 Sequelize 中包含模型