【问题标题】:How to update subdocument and delete single object of array in subdocument?如何更新子文档并删除子文档中的单个数组对象?
【发布时间】:2017-05-17 21:24:31
【问题描述】:

这是我拥有的对象:

{
  "_id": ObjectId("590985b1859aefea4a39982f"),
  "comment": [{
    "created_at": 1493880257678.0,
    "comment": "12345",
    "user_id": ObjectId("58edd98d40627c492c8689c5"),
    "_id": ObjectId("590acdc1141b16c6521b9140"),
    "modified": 1493880257678.0,
    "assigned_to": null
  }, {
    "created_at": 1493880257678.0,
    "comment": "12345",
    "user_id": ObjectId("5906c50c1be98711121edf2b"),
    "_id": ObjectId("590acdc1141b16c6521b9140"),
    "modified": 1493880257678.0,
    "assigned_to": null
  }, {
    "created_at": 1493880257678.0,
    "comment": "12345",
    "user_id": ObjectId("58edd98d40627c492c8689c5"),
    "_id": ObjectId("590acdc1141b16c6521b9140"),
    "modified": 1493880257678.0,
    "assigned_to": null
  }]
}

我想删除user_id(58edd98d40627c492c8689c5)的评论子文档

【问题讨论】:

  • 您能否将问题编辑为更简洁一点

标签: javascript node.js mongodb mongoose mongodb-query


【解决方案1】:

您可以将 findOneAndUpdate 与 $pull 一起使用。

您将像这样构建您的查询。

findOneAndUpdate(
{_id: <id of the document>}, 
{$pull: {comment: {user_id: <user_id>}}}, 
{multi:true}
)

不确定您使用的是什么客户端或驱动程序,但这是我在 robomongo 上进行的示例测试,集合名称为“documents”

db.getCollection('documents').findOneAndUpdate(
{_id: new ObjectId("590985b1859aefea4a39982f")}, 
{$pull: 
   {comment:{user_id : new ObjectId("58edd98d40627c492c8689c5")}}
}, 
multi:true})

【讨论】:

    猜你喜欢
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2019-08-02
    • 1970-01-01
    • 2020-12-11
    • 2023-03-28
    • 2016-11-04
    相关资源
    最近更新 更多