【问题标题】:How to delete nested array elements in mongo Db如何删除mongoDb中的嵌套数组元素
【发布时间】:2017-05-24 13:50:48
【问题描述】:

“如何从 mongo db 的结构(也显示在图像上)中删除嵌套数组 'accounts' 中的单个元素。我可以使用 $pull 方法吗?任何知道的人请分享你的想法”。

 "associatedAccounts" : [ 
        {
            "organizationId" : "5808ba773fe315441b9e0a9e",
            "_id" : ObjectId("5808bc0c3fe315441b9e0b1a"),
            "accounts" : [ 
                "5808baf33fe315441b9e0aa7", 
                "5808baf33fe315441b9e0aa8", 
                "5808baf33fe315441b9e0aa1"
            ]
        }, 
        {
            "organizationId" : "5808ba773fe315441b9e0a9f",
            "_id" : ObjectId("5808bc0c3fe315441b9e0b1b"),
            "accounts" : [ 
                "5808baf33fe315441b9e0aa3", 
                "5808baf33fe315441b9e0aa2", 
                "5808baf33fe315441b9e0aa5", 
                "5808baf33fe315441b9e0aa6"
            ]
        }
    ]

,

【问题讨论】:

标签: arrays node.js mongodb nested-attributes


【解决方案1】:

你可以在_id的基础上删除,因为Id在Mongodb中是唯一标识

 db.stores.update(
 {_id:id  },  //set accounts Id which you want to update
 {$pull:{
        "associatedAccounts":{
                  "_id"accountsId // the unique _id from the objects in arrray  
                   }
        }
 })

accountsId 将是来自 associatedAccounts 的唯一 ID,即此数组中存在的每个对象的 _id。

$pull 将删除 id 与查询匹配的特定对象。

【讨论】:

  • 这是一个错误的方法,它不适用于我提到的场景
猜你喜欢
  • 2019-01-25
  • 1970-01-01
  • 2017-05-18
  • 2022-11-16
  • 1970-01-01
  • 2013-11-22
  • 2021-02-26
  • 1970-01-01
相关资源
最近更新 更多