Node.js Mongodb在条件下从数组取消设置

Node.js Mongodb在条件下从数组取消设置,node.js,mongodb,Node.js,Mongodb,我有这样的用户集合: [ { "_id": ObjectId("5f40feac77514e76dd49950b"), "name": "Max", "email": "test@test.us", "cart": { "products": [ {

我有这样的用户集合:

[
{
    "_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
            }
        ]
    }
}
]
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匹配的项目。 我试过这样的方法:

[
{
    "_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
            }
        ]
    }
}
]
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的产品。

您可以使用来完成此操作:

await db.collection('users').update(
    {},
    { $pull: { "cart.products": { productId } } },
    { multi: true }
});
您可以使用来完成此操作:

await db.collection('users').update(
    {},
    { $pull: { "cart.products": { productId } } },
    { multi: true }
});