如何删除嵌入在 MongoDB 子数组中的子文档(按 Id)?

elv*_*vin 0 pull mongodb subdocument

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'} }
            ]
},
Run Code Online (Sandbox Code Playgroud)

我想从集合 (x1) 中删除子文档 (xxx3),然后尝试以下操作:

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

这似乎不起作用。谁能帮帮我吗?谢谢

kmd*_*eko 6

的字段$pull必须是数组。

这应该有效:

$pull: { products: { 'product.id': 'xxx3' } }
Run Code Online (Sandbox Code Playgroud)