【问题标题】:Check if ALL the update operations resulted in modification in MongoDB检查所有更新操作是否导致 MongoDB 中的修改
【发布时间】:2020-09-11 22:43:08
【问题描述】:

我在 MongoDB 和 nodejs 的多个集合中关注了这个 article on using transaction。经过多次尝试和失败,我发现事务仅适用于 ReplicaSet。所以我决定修改我的架构,以便我可以处理单个文档更新。

我的架构有点像这样,

// collection "products"
{
  shop: 'ShopID1',
  customer: ['CustomerID1', 'CustomerID2'],
  products: [
    {product: 'ProductID1', productCount: 10, customer: ['CustomerID1']} ....
  ]
}

因此,基本上,当customer 购买product 时,我想减少其productCount 并将它们添加到特定产品customer 数组和商店客户数组中。客户只有在产品数量 > 0 时才能购买产品。另一个限制是,客户只能从商店购买 ONE 产品。

我已经为此找到了以下更新查询,

db.collection('products').updateOne(
        { shop: shopName},
        { 
            $inc: {'products.$[elem].productCount': -1},
            $addToSet: {
                'products.$[elem].customers': customerId,
                'customers': customerId,
            },
        },
        { 
            arrayFilters: [ {"elem.product": productId, "elem.productCount": {$gt: 0}} ],
        },
    );

此更新操作适用于有效场景(产品可用且客户尚未从商店购买任何东西)。但在无效场景下会失败。

我可以检查购买是否有效的一种方法是检查每个单独的更新是否导致修改。有什么方法可以检查 3 个更新操作中的每一个是否成功,如果没有以某种方式恢复更新?我也很感激处理这种情况的替代建议。谢谢。

注意:我正在使用 MongoDB 4.4 服务器并通过 NodeJS 使用 mongo 客户端 3.6 访问它

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    updateOne 返回已更改文档的数量。

    MongoDB Enterprise mongos> db.products.updateOne(         { shop: 'shopName'},         {              $inc: {'products.$[elem].productCount': -1},             $addToSet: {                 'products.$[elem].customers': 'customerId',                 'customers': 'customerId',             },         },         {              arrayFilters: [ {"elem.product": 'productId', "elem.productCount": {$gt: 0}} ],         },     );
    { "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }
    

    【讨论】:

    • 是的。但我需要知道更新“字段”的数量。如果其中一个字段未更新,那么我会将其视为无效操作。当我开始学习 mongo 时,此实现非常笨拙。我会考虑一个更好的模型来处理这种情况
    • 如果满足查找条件,您在更新文档中或作为更新运算符提供的所有内容都会写入数据库。
    • 是的。我认为我指定的查找条件并不完全正确。我尝试使用 elemMatch,它提供了更好的响应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 2019-10-04
    • 1970-01-01
    • 2013-04-16
    • 2021-06-24
    相关资源
    最近更新 更多