问题
我有一个连接到 MongoDB 的 NodeJS 应用程序。我正在追踪某件事发生了多少次。所以,我想要的是:
- 检查我构造的对象是否在数据库中(不包括出现次数的字段)
- 如果是,则更新其出现次数 +=1
- 如果没有,则设置occurrences = 1并插入它
我有一个工作代码:
const isInDb = await collection.findOne({
// match all other fields except for the occurrences field
});
if(!isInDb) {
parsedElement.occurrences = 1;
await collection.insertOne(parsedElement);
} else {
await collection.updateOne(isInDb, { $inc: { "occurrences": 1 } });
}
我的问题
难道就没有更好的办法了吗?理想情况下,它应该类似于 collection.findAndUpdate 或 upsert 或类似的东西。我写的内容是有用的,但对我来说似乎效率低下,因为我首先必须查询数据库进行查找,然后查询它进行更新。
最佳答案
updateOne 采用第三个参数作为选项。设置 upsert: true。
collection.updateOne({ /* match properties */ }, { $inc: { "occurrences": 1 } }, { upsert: true })
关于node.js - MongoDB 在数据库中查找一个对象并更新其字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52915919/