从MongoDB 2.4开始,不再需要
findOrCreate像原子操作那样依赖唯一索引(或任何其他解决方法)。
这要归功于2.4新增的
$setOnInsert运算符,该运算符使您可以指定仅在插入文档时进行的更新。
结合使用该
upsert选项,意味着您可以
findAndModify用来实现
findOrCreate类似原子的操作。
db.collection.findAndModify({ query: { _id: "some potentially existing id" }, update: { $setOnInsert: { foo: "bar" } }, new: true, // return new doc if one is upserted upsert: true // insert the document if it does not exist})因为
$setOnInsert仅影响插入的文档,所以如果找到现有文档,则不会进行任何修改。如果没有文档,它将使用指定的_id向上插入一个文档,然后执行仅插入集。在两种情况下,都将返回文档。



