繁体   English   中英

如何更新子文档并删除子文档中数组的单个对象?

[英]How to update subdocument and delete single object of array in subdocument?

这是我所拥有的对象:

{
  "_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)

您可以将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})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM