我收集了一些论坛帖子,(大致)看起来像
{
"author": author,
"date": new Date(),
"content": req.body.content,
"comments":{
"deleted": 0,
"author": author,
"date": new Date(),
"content": req.body.content
}
}
如果用户添加评论,它会简单地 $pushed 到当前评论。
现在我想要删除一个特定评论的可能性。 我插入了“已删除”标志以管理员身份查看评论,而不是完全删除它们。
但问题是:我如何告诉 mongoDB 我想删除哪条评论?
我刚刚添加了一个“commentID”字段,但我不知道如何自动递增它(文档对此真的很奇怪), 在查询中尝试了很多类似“comments.toDeleteId”或“comments[toDeleteId]”的东西之后。
TLDR:我如何查询帖子“34563456354”、评论“5”、$set“deleted”为“1”,其中评论本身是一个数组?
谢谢
编辑
这是帖子的 console.dir:
{_id: //etc etc
op: 'Anonymous',
postContent: 'testtest',
createdAt: //etc,
comments:
[ { deleted: 0,
posted: //etc,
author: 'Anonymous',
comment: 'test' },
{ deleted: 0,
posted: //etc,
author: 'Anonymous',
comment: 'testtesttest' } ]
最佳答案
在更新中使用 $elemMatch 如下:
db.collectioName.update({
"_id": ObjectId("55ba6729eb5f4a21914568df"),
"comments": {
"$elemMatch": {
"comment": "testtesttest"
}
}
}, {
"$set": {
"comments.$.deleted": 1
}
})
或者如果你想增加 deleted
然后使用 $inc as :
db.collectionName.update({
"_id": ObjectId("55ba6729eb5f4a21914568df"),
"comments": {
"$elemMatch": {
"comment": "testtesttest"
}
}
}, {
"$inc": {
"comments.$.deleted": 1
}
})
如果您想在 comment
中推送新对象,请在更新中使用 $push
作为:
db.collectionName.update({
"_id": ObjectId("55ba6729eb5f4a21914568df")
}, {
"$push": {
"comments": {
"deleted": 1,
"posted": new Date(),
"author": "ABC",
"comment": "tests"
}
}
})
关于arrays - 如何修改 mongoDB 中的子条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31730471/