Remove element from nested array mongodb

前端 未结 2 1577
时光说笑
时光说笑 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: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 $[] 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 }
    )
    

提交回复
热议问题