如何修改mongoDB中的子项

我有一个论坛post的集合,看(大致)像

{ "author": author, "date": new Date(), "content": req.body.content, "comments":{ "deleted": 0, "author": author, "date": new Date(), "content": req.body.content } } 

如果用户添加评论,则简单地推送到当前评论。

现在我想要删除一个特定评论的可能性。 我插入了“已删除”标志,以pipe理员身份查看评论,而不是完全删除它们。

但问题是:我如何告诉mongoDB哪个确切的评论我想删除?

我刚刚添加了一个“commentID”字段,但我不知道如何自动递增它(文档真的很奇怪),尝试了很多像“comments.toDeleteId”或“评论[toDeleteId]“。

TLDR:如何查询post“34563456354”,评论“5”,$设置“删除”为“1”,其中评论是一个数组本身?

谢谢

编辑

这是一个post的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然后使用$公司作为:

 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" } } }) 

我实际上find了一种方法来做到这一点,即使我之前search过,没有find该线程。

做到这一点其实很简单,一开始就很难把握。

 var selector = {}; var operator = {}; selector['comments.' + commentId + '.deleted'] = 1; operator['$set'] = selector; 

这给了我一个

 {'$set': {'comments.2.deleted': 1 } } 

我可以很容易地插入到查询的地方

 {_id: thisId, operator, cb) 

(学分https://stackoverflow.com/a/19115944/4547337