Search code examples
mongodbpullsubdocument

How to remove subdocument (by Id) embedded in sub array in MongoDB?


ProductCollection: 
{
  _id: { ObjectId('x1')},
  products: [ 
              { listPrice: '1.90', product: {id: 'xxx1'} },
              { listPrice: '3.90', product: {id: 'xxx2'} },
              { listPrice: '5.90', product: {id: 'xxx3'} }
            ]
},
{
  _id: { ObjectId('x2')},
  products: [ 
              { listPrice: '2.90', product: {id: 'xxx4'} },
              { listPrice: '4.90', product: {id: 'xxx5'} },
              { listPrice: '5.90', product: {id: 'xxx6'} }
            ]
},

I want to remove subdocument (xxx3) from collection (x1), and try below:

ProductCollection.update(
{ 
  "_id": mongoose.Types.ObjectId('x1')  
}, 
{ 
  $pull : { 'products.product': {id: 'xxx3' } } 
} 

It just doesn't seem to work. Can anyone please help me? Thank you


Solution

  • The field for $pull needs to be the array.

    This should work:

    $pull: { products: { 'product.id': 'xxx3' } }