arrays - 如何修改 mongoDB 中的子条目

标签 arrays node.js mongodb

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

{
"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/

相关文章:

arrays - Swift数组中最大值及其索引的高效算法

javascript - 如何使 Sequelize 批量创建 x 条相同记录,仅增加日期?

mongodb - 如何在 MongoDB 中进行嵌套 $lookup 搜索?

arrays - 在 Swift 中向可选数组添加元素

javascript - 如何组合两个数组的属性?

John Resig 的 Javascript Array.remove() - 为什么它在 for-in 语句中枚举?

arrays - 如何在MongoDB中批量迭代?

arrays - 如果数组包含 id mongoose 则获取数组

node.js - 部署部署到 Heroku 仪表板 key

mongodb - 通过 Scala Play 连接时如何解决 MongoDB 超时错误!框架?