Remove element from nested array mongodb

前端 未结 2 1564
时光说笑
时光说笑 2020-12-12 03:16

i have the following document , it has two array\'s , one inside the other ,
attachment array and files array inside attachment array . i want to delete an element insi

相关标签:
2条回答
  • 2020-12-12 03:24

    You can try below update query in 3.6 version.

    Invoice.update( 
     {}, 
     {"$pull":{"attachment.$[].files":{_id:ObjectId("5b7969ac8fb15f3e5c8e844e")}}}, 
     {"multi": true}, function (err, result) {console.log(result);
    });
    

    Use db.adminCommand( { setFeatureCompatibilityVersion: 3.6 or 4.0 depending on your version } ) if your are upgrading from old version.

    0 讨论(0)
  • 2020-12-12 03:34

    For Mongodb version prior to 3.6

    There is only one nested level here so you can simply use $ positional operator.

    Invoice.update(
      { "attachment.files._id": mongoose.Types.ObjectId("5b7937014b2a961d082de9bf") },
      { "$pull": { "attachment.$.files": { "_id": mongoose.Types.ObjectId("5b7937014b2a961d082de9bf") }}},
      { "multi": true }
    )
    

    For Mongodb version 3.6 and above

    If you want to update multiple elements inside attachement array then you can use $[] the all positional operator.

    const mongoose = require("mongoose")
    
    Invoice.update(
      { "attachment.files._id": mongoose.Types.ObjectId("5b7937014b2a961d082de9bf") },
      { "$pull": { "attachment.$[].files": { "_id": mongoose.Types.ObjectId("5b7937014b2a961d082de9bf") }}},
      { "multi": true }
    )
    

    And If you want to update single element inside the attachment array then you can use $[<identifier>] that identifies the array elements that match the arrayFilters conditions.

    Suppose you want to update only an element inside attachment having _id equal to ObjectId(5b7934f54b2a961d081de9ab)

    Invoice.update(
      { "attachment.files._id": mongoose.Types.ObjectId("5b7937014b2a961d082de9bf") },
      { "$pull": { "attachment.$[item].files": { "_id": mongoose.Types.ObjectId("5b7937014b2a961d082de9bf") } } },
      { "arrayFilters": [{ "item._id": mongoose.Types.ObjectId("5b7934f54b2a961d081de9ab") }], "multi": true }
    )
    
    0 讨论(0)
提交回复
热议问题