【问题标题】:How to modify a child entry in a mongoDB如何修改 mongoDB 中的子条目
【发布时间】:2015-07-31 04:49:16
【问题描述】:

我收集了一些论坛帖子,看起来(大致)像

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

如果用户添加评论,它只是 $pushed 到当前的 cmets。

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

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

我刚刚添加了一个“commentID”字段,但我不知道如何自动增加它(文档对此真的很奇怪), 在查询中尝试了很多诸如“cmets.toDeleteId”或“cmets[toDeleteId]”之类的东西之后。

TLDR:我如何查询帖子“34563456354”,评论“5”,$set“deleted”为“1”,其中 cmets 本身就是一个数组?

谢谢

编辑

这是一个帖子的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' } ]

【问题讨论】:

  • comments 数组还是对象?
  • 我刚刚检查过,它确实是一个数组,包含对象。我将更新问题中的 console.dir
  • 你应该使用另一个评论集合,然后用它填充论坛帖子。
  • 有没有办法只插入一个自增字段?那将解决我的问题。比如“把它推到 cmets 上,增加 ID,谢谢”?
  • @PaulSchneider 这里有些混乱你想设置什么deleted:1comment: 'testtesttest'?或者您想在comments 数组中推送新对象?或将deleted 增加到 1 其中comment: 'testtesttest'

标签: arrays node.js mongodb


【解决方案1】:

在更新中使用$elemMatch,如下所示:

db.collectioName.update({
"_id": ObjectId("55ba6729eb5f4a21914568df"),
"comments": {
    "$elemMatch": {
        "comment": "testtesttest"
    }
}
}, {
"$set": {
    "comments.$.deleted": 1
}
})

或者如果你想增加deleted,那么使用$inc

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

【讨论】:

  • 但我想通过他们的索引删除 cmets。比如“删除第三条评论”。请参阅下面的有效解决方案,但感谢您的努力。我要研究 $elemMatch,这对于我计划的一些事情看起来很有希望。
【解决方案2】:

我实际上已经找到了一种方法来做到这一点,即使我之前搜索过并没有找到那个线程。

方法其实很简单,但一开始很难掌握。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    相关资源
    最近更新 更多