首先,我將展示存盤在mongodb.

如您所見,它是一個結構體,其中包含一個名為replies的串列comments。里面replies有一個名為likes.
comments : [
Object1 : {
replies : [
likes : [
0 : {},
1 : {}
]
]
},
Object2 : {
replies : [
likes : [
0 : {},
1 : {}
]
]
}
]
我想在這里做的是僅從likes特定replies結構內的陣列中插入/減去一個值。我目前正在使用 Spring Boot 并嘗試了以下操作:
Query query = new Query();
Criteria criteria = Criteria.where("_id").is(new ObjectId(postId))
.andOperator(Criteria.where("comments")
.elemMatch(Criteria.where("_id").is(new ObjectId(commentId))
.andOperator(Criteria.where("replies")
.elemMatch(Criteria.where("_id").is(new ObjectId(replyId)))
)
)
);
query.addCriteria(criteria);
Update update = new Update();
if (state) {
// remove user id
update.pull("comments.$[].replies.$.likes", new ObjectId(userId));
} else {
// add user id
update.push("comments.$[].replies.$.likes").value(new ObjectId(userId));
}
mongoTemplate.updateFirst(query, update, MyEntity.class);
是userId根據 boolean添加或洗掉的操作state。作為嘗試的結果,到特定的comment被發現,但userId在第一無條件地進入likes該名單replies內的清單comment。我想要的是進入likes特定reply. 我在 中使用了錯誤的引數update.push()嗎?如果您能告訴我如何解決它,我將不勝感激。
uj5u.com熱心網友回復:
不是直接回答您的問題,因為我沒有使用 spring 的標準構建器的經驗,但這里是您如何直接在 mongo 中執行此操作的方法,這可能會幫助您弄清楚:
您可以定義arrayfilters允許您跟蹤每個comments和的相應索引replies。然后,您可以使用這些索引在完全匹配的索引處推送新物件:
db.collection.update({
_id: "<postId>"
},
{
$push: {
"comments.$[comments].replies.$[replies].likes": {
_id: "newlyInsertedLikeId"
}
}
},
{
arrayFilters: [
{
"comments._id": "<commentId>"
},
{
"replies._id": "<replyId>"
}
]
})
這是 mongoplayground 的示例:https ://mongoplayground.net/p/eNdDXXlyi2X
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360705.html
