【问题标题】:Deleting an item with condition in MongoDB?在 MongoDB 中删除有条件的项目?
【发布时间】:2021-09-30 15:21:07
【问题描述】:

我想通过检查产品的数量从购物车中删除产品。它的数量应该减1,直到它达到零,然后,它应该从Cart的产品数组中拉出。

这是我的逻辑:(我想在单个查询中执行拉取和递减操作。但我被困在如何通过 MongoDb 中的一个简单条件一起执行这两个操作)

const cart = await Cart.findOneAndUpdate({"products.productId": req.body.productId}, {$inc: {"products.$.quantity": -1}}, {new: true})
         
await Cart.update({"products.productId": req.body.productId}, {$pull: {quantity: 0}})

这里是澄清的模型:

import mongoose from 'mongoose';

const cartSchema = new mongoose.Schema({
    userId: {
        type: String,
        required: true,
    },
    products: [
        {
            productId: {
                type: String,
            },
            quantity: {
                type: Number,
                default: 1
            }

        }

    ]
    
}, {timestamps: true});
const Cart = new mongoose.model('Cart', cartSchema);

export default Cart;

谢谢:)

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    在单个常规更新查询中没有直接的方法可以做到这一点。

    要改进你的方法,你可以试试这个,

    • 第一个查询检查productIdquantity 应该大于1
    const cart = await Cart.updateOne(
      { 
        products: {
          $elemMatch: {
            productId: req.body.productId,
            quantity: { $gt: 1 }
          }
        }
      }, 
      { $inc: { "products.$.quantity": -1 } }
    );
    

    Playground

    • 第二个查询如果第一个查询的结果是nModified是0然后拉产品,通过检查条件productIdquantity等于1
    if (cart.nModified === 0) {
      await Cart.updateOne(
        { 
          products: {
            $elemMatch: {
              productId: req.body.productId,
              quantity: { $eq: 1 }
            }
          }
        }, 
        { $pull: { products: { productId: req.body.productId } } }
      )
    }
    

    Playground


    如果你真的想使用单个查询,你可以从 MongoDB 4.2 开始尝试update with aggregation pipeline

    • $map 迭代 products 数组的循环并检查条件,如果 productId 匹配,则通过 $add 运算符递增/递减 quantity 否则返回当前数量
    • $filter 迭代上述结果的循环并检查 productIdquantity 是否不为零的条件
    await Cart.updateOne(
      { "products.productId": req.body.productId },
      [{
        $set: {
          products: {
            $filter: {
              input: {
                $map: {
                  input: "$products",
                  in: {
                    productId: "$$this.productId",
                    quantity: {
                      $cond: [
                        { $eq: ["$$this.productId", req.body.productId] },
                        { $add: ["$$this.quantity", -1] },
                        "$$this.quantity"
                      ]
                    }
                  }
                }
              },
              cond: {
                $and: [
                  { $eq: ["$$this.productId", req.body.productId] },
                  { $ne: ["$$this.quantity", 0] }
                ]
              }
            }
          }
        }
      }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-15
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 2014-06-28
      • 2021-10-31
      相关资源
      最近更新 更多