我有这样的用户集合:
[
{
"_id": ObjectId("5f40feac77514e76dd49950b"),
"name": "Max",
"email": "test@test.us",
"cart": {
"products": [
{
"productId": ObjectId("5f40f79f3b324fbaf85567a5"),
"cnt": 1
},
{
"productId": ObjectId("somethingrandom"),
"cnt": 2
}
]
}
},
{
"_id": ObjectId("whatever"),
"name": "John",
"email": "test@test.us",
"cart": {
"products": [
{
"productId": ObjectId("5f40f79f3b324fbaf85567a5"),
"cnt": 1
},
{
"productId": ObjectId("somethingrandom2"),
"cnt": 2
}
]
}
}
]
我想要通过每一个用户购物车中的每一个产品,并从产品中删除匹配ID的项目。我试过这样的方法:
const productId = new ObjectId('5f40f79f3b324fbaf85567a5');
await db.collection('users').updateMany({
'cart.products.productId': productId
},{
$unset:{
'cart.products.':null ///i don't know what should be here
}
});
我不想删除所有的产品从购物车,但只有这些有相同的ID。
您可以使用$pull
-运算符来完成此操作:
await db.collection('users').update(
{},
{ $pull: { "cart.products": { productId } } },
{ multi: true }
});