node.js - MongoDB 递增/递减或 upsert
问题描述
我正在尝试减少文档中的字段并设置默认值(如果它不存在)。我的查询如下:
usersCollection.findOneAndUpdate(
{_id: id},
{
$inc: {quota: -1},
$setOnInsert: {quota: 100}
},
{
upsert: true,
returnOriginal: false
}
)
但是这个查询给出了以下错误:
更新路径“配额”会在“配额”处产生冲突
如果我不使用,$setOnInsert: {quota: 100}
那么它可以工作,但会从我不想要的 0 开始递减。我的目标是在这种情况下设置一个默认值 (100) 并在每个查询上递减。这可能在 1 个查询中吗?我四处寻找,但没有找到可以提供帮助的东西。
解决方案
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
推荐阅读
- server - 可靠的“测试”服务器无法打开 XAMPP
- docker - 无法使用 Kaniko 构建运行 docker 映像(基于 Webshpere liberty)
- python - 使用正则表达式获取带句点的电话号码
- scala - 转换字符串序列以连接列
- mysql - 如何消除工作台中的错误?
- python - 酌情将行从一个数据帧分配到另一个数据帧
- python - 球体上三角形的六边形:从二十面体网格构建六边形/测地线网格(仅限北极)
- vba - 如何将项目添加到包含分号的组合框(使用 AddItem())?
- javascript - 如何编写分组算法,通过具有 3 个或更多相似属性对数据集中的项目进行分组
- r - 计算字符串出现在组列中的次数