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

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'} }
            ]
},

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

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

这似乎行不通。谁能帮帮我吗?谢谢

$pull 的字段必须是数组。

这应该有效:

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

在创建猫鼬模式时添加此 _id: {id: false}

例如:

partners:[{
    name: { type: String, default: '' },
    logo: { type: mongoose.Schema.Types.Mixed, default: '' },
    _id: { id: false }
  }],