首页 > 解决方案 > MongoDB 递增/递减或 upsert

问题描述

我正在尝试减少文档中的字段并设置默认值(如果它不存在)。我的查询如下:

 usersCollection.findOneAndUpdate(
    {_id: id},
    {
        $inc: {quota: -1},
        $setOnInsert: {quota: 100}
    },
    {
        upsert: true,
        returnOriginal: false
    }
)

但是这个查询给出了以下错误:

更新路径“配额”会在“配额”处产生冲突

如果我不使用,$setOnInsert: {quota: 100}那么它可以工作,但会从我不想要的 0 开始递减。我的目标是在这种情况下设置一个默认值 (100) 并在每个查询上递减。这可能在 1 个查询中吗?我四处寻找,但没有找到可以提供帮助的东西。

标签: node.jsmongodb

解决方案


I do not believe this is possible in a single query, as it contains an atomic operation ($inc) and contains two potential operations on the same field. (This would explain the 'quota' error message.)

You could use two different queries with the $exists operator to determine how the quota field should


推荐阅读