首页 > 解决方案 > 使用更新拉取从数组中删除一个元素的问题

问题描述

我正在使用 mongoose 和 express 作为我的后端,我正在尝试从单个 Mongodb 文档中的订单数组中删除一个数组元素。这可能吗?我在网上搜索过,但只找到了如何使用过滤器删除所有元素或弹出数组中的第一个或最后一个元素。

目前我正在后端执行此操作,但是这会删除 item_id 等于 data.response[0].item_id 的每个订单元素。

user.updateOne({ "username": data.username },{"$pull": { "orders": {"item_id": data.response[0].item_id}}},{safe: true });

这行代码在 item_id 为 1 时删除订单内的两个元素但是我只希望它删除它找到的第一个元素 item_id: 1

用户集合的示例 Mongodb 文档部分

{
        "_id": "60a906402342852b483341a6",
        "username": "qwer",
        "password": "qwer",
        "orders": [
            {
                "_id": "609cf4d4e4ecce2348139686",
                "item_id": 1,
                "item_name": "toothbrush",
                "item_price": 28,
                "item_category": "dental",
                "item_currency": "$",
                "item_description": "standard toothbrush",
                "item_image": "https://cdn.shopify.com/s/files/1/1704/0849/products/ToothBrushTeal_bc4c6c15-cf79-4bb5-87cc-28109b5e7605_1024x1024.jpg?v=1607029152"
            },
            {
                "_id": "609cf4d4e4ecce2348139686",
                "item_id": 1,
                "item_name": "toothbrush",
                "item_price": 28,
                "item_category": "dental",
                "item_currency": "$",
                "item_description": "standard toothbrush",
                "item_image": "https://cdn.shopify.com/s/files/1/1704/0849/products/ToothBrushTeal_bc4c6c15-cf79-4bb5-87cc-28109b5e7605_1024x1024.jpg?v=1607029152"
            }
    ]
}

标签: node.jsmongoose

解决方案


您可能想查看此论坛https://developer.mongodb.com/community/forums/t/pull-only-one-item-in-an-array-of-instance-in-mongodb/12928 使用聚合更新,如第一个答案所示。你的代码应该是这样的:

user.updateOne({ "username": data.username },[ 
{ $set: { 
     orders: {
         $let: {
             vars: { ix: { $indexOfArray: [ "$orders", data.response[0].item_id ] } },
             in: { $concatArrays: [
                       { $slice: [ "$orders", 0, "$$ix"] },
                       [ ],
                       { $slice: [ "$orders", { $add: [ 1, "$$ix" ] }, { $size: "$orders" } ] }
                  ]
             }
        }
    }
}}],{safe: true });

推荐阅读