Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove all array element in mongodb which has id match in array

I have an array of the id which I get from post request in nodejs. I want to remove all the elements in the orders array which match receive id array.

eg remove_id = [’60f1ab20891ced4818b5ea88′,’60f1ab20891ced4818b5ea87′]
so I want to remove all elements from orders array whoose id match match remove_id array.

orderdetail = {
  _id: 60f1ab20891ced4818b5ea86,
  totalPrice: 400,
  orders: [
    {
      _id: 60f1ab20891ced4818b5ea87,
      quantity: 1,
      price: 200,
      name: 'Caramel Latte',
      category: 'Steaming Cups'
    },
    {
      _id: 60f1ab20891ced4818b5ea88,
      quantity: 1,
      price: 200,
      name: 'Cinnamon Latte',
      category: 'Steaming Cups'
    },
    {
      _id: 60f1ab20891ced4818b5ea89,
      quantity: 1,
      price: 200,
      name: 'Cinnamon Latte',
      category: 'Steaming Cups'
    }
  ],
  timestamp: 1626450720332,
  name: 'xxx',
  email: 'xxx',
}

what I have tried but not working,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Orderdetail.updateOne( { _id: '60f1ab20891ced4818b5ea86' }, { 
        $pull: { order: { _id: { $in: remove_id  } } } } )

>Solution :

Rename object name order to orders !

Try this code !

let remove_id = ['60f1ab20891ced4818b5ea87','60f1ab20891ced4818b5ea88']
db.getCollection('Orderdetail').updateOne({ _id: '60f1ab20891ced4818b5ea86' }, {
  $pull: {
    orders: { // rename this to orders 
      _id: { $in: remove_id }
    }
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading