【问题标题】:How to delete all sub array如何删除所有子数组
【发布时间】:2021-06-09 07:02:48
【问题描述】:

在我的 MongoDB 数据库中,我有一个包含此类文档的“产品”集合

{
    "_id": {
        "$oid": "6048e97b4a5f000096007505"
    },
    "modeles": [
        {
            "id": "OppoA3",
            "pieces": [
                {
                "id": "OppoA3avn"      
                },
                {
                 "id": "OppoA3bat"      
                }]
            ]
        }, 
        {
            "id": "OppoA1",
            "pieces": [
                {
                "id": "OppoA1avn",
                },
                {
                "id": "OppoA1batt",
                }
            ]
        }
    ]
}

如何从我的所有文档中删除所有 modeles.pieces。

我设法在 modeles.id 上使用过滤器删除,但使用该代码但不是在所有集合中删除

db.produits.update(
    {marque_id:'OPPO', 'modeles.id':'RENOZ'},
    {$set:
        {
            'modeles.$.pieces': []
        }
    }
    , { multi : true }
)

我最终想要所有这样的文件

{
    "_id": {
        "$oid": "6048e97b4a5f000096007505"
    },
    "modeles": [
        {
            "id": "OppoA3",
            "pieces": []
        }, 
        {
            "id": "OppoA1",
            "pieces": []
        }
    ]
}

感谢您的帮助。

【问题讨论】:

    标签: arrays mongodb mongoose


    【解决方案1】:
        db.produits.update({
          modeles: {//This is because your second document will create failure otherwise
            $exists: true
          }
        },
        {
          $set: {
            "modeles.$.pieces": []
          }
        },
        {
          multi: true
        })
    

    【讨论】:

    • 我试过了,但不可能Error : The positional operator did not find the match needed from the query.
    • 当然,你只需要将它重置为空数组。一定要测试这个逻辑,确保它符合你的需要。
    • 还有错误"code" : 28, "errmsg" : "Cannot create field 'pieces' in element {modeles: [
    • 请在您的答案中添加一些解释,以便其他人可以从中学习
    • 我更新了我的编辑问题,因为我的示例文档格式错误
    【解决方案2】:

    我已经做了一个这样的 javascript 循环,但我认为这不是最佳实践

     async removePieces(){
        var doc
        try {
          doc =  await produitModel.find()
          for (var produit of doc) {
            for (var modele of produit.modeles) {
              const filter = {'marque_id': produit.marque_id, 'modeles.id': modele.id}
              const set = {
                            $set: {
                              'modeles.$.pieces': []
                            }
                          }
    
              await db.collection('produits').updateOne(filter, set)
            }
          }
          console.log('removePieces() ==> Terminé')
        } catch(err) {
          console.log(err)
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2013-05-28
      • 2014-04-20
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 2013-04-06
      • 1970-01-01
      • 2012-06-22
      相关资源
      最近更新 更多