我有一个示例 Post
集合
[{
"_id" : ObjectId("5da832caeb173112348e509b"),
"body" : "Lorem Ipsu.",
"comments" : [
{
"comment" : "my sample comment",
"_id" : ObjectId("5db06e11d0987d0aa2cd5593"),
"replies" : [
{
"likes" : [
"5d999578aeb073247de4bd6e",
"5da85558886aee13e4e7f044"
],
"_id" : ObjectId("5db6a88f7c6cfb0d0c2b689b"),
"reply" : "my reply to this comment",
"user" : "5da85558886aee13e4e7f044"
}
],
"likes" : [
"5da85558886aee13e4e7f044",
]
},
],
}]
要将添加
或删除
元素添加到comments.likes
中,我可以这样做,$push
或$pull
,它适用于以下操作。
Post.updateOne(
{_id: req.body.id_post, "comments._id": req.body.id_comment},
{ $push: {"comments.$.likes": req.user._id}});
但是如果我想push
到replies.likes
,有人可以帮助指导我吗?
我尝试过类似的操作,但 replies.likes
未更新。
db.posts.updateOne(
{ "comments.replies._id": Object("5db6a88f7c6cfb0d0c2b689b") },
{ "$push": { "comments.0.replies.$.likes": Object("5db6a88f7c6cfb0d0c2b689a") } },
function(err,numAffected) {
// something with the result in here
}
);
您可以使用数组过滤器:
db.getCollection("test").updateOne(
{
"comments.replies": {
"$elemMatch": {
"_id": Object("5db6a88f7c6cfb0d0c2b689b")
}
}
},
{ "$set": { "comments.$[outer].reply.$[inner].likes": Object("5db6a88f7c6cfb0d0c2b689a") } },
{
"arrayFilters": [
{ "outer._id": ObjectId("5cd26a886458720f7a66a413") },
{ "inner._id": ObjectId("5cd26a886458720f7a66a415") }
]
}
)
不介意 ID
我是一名优秀的程序员,十分优秀!