【发布时间】:2012-02-09 07:00:33
【问题描述】:
如果文档不存在,我需要插入它。我知道“upsert”选项可以做到这一点,但我有一些特殊需求。
首先,我只需要创建带有 _id 字段的文档,但前提是它不存在。我的 _id 字段是我生成的数字(不是 ObjectId)。如果我使用“upsert”选项,那么我会得到“Mod on _id not allowed”
db.mycollection.update({ _id: id }, { _id: id }, { upsert: true });
我知道我们不能在 $set 中使用 _id。
所以,我的问题是:如果有任何方法可以在 mongodb 中原子地“创建如果不存在”?
编辑: 正如@Barrie 所提议的那样(使用 nodejs 和 mongoose):
var newUser = new User({ _id: id });
newUser.save(function (err) {
if (err && err.code === 11000) {
console.log('If duplicate key the user already exists', newTwitterUser);
return;
}
console.log('New user or err', newTwitterUser);
});
但我仍然想知道这是否是最好的方法。
【问题讨论】:
-
尝试使用
save操作?即 db.collection.save({"_id": your_id}) -
如果已存在,则保存失败并出现重复键错误
标签: mongodb