MongoDB原子"findOrCreate":findOne,如果不存在则插入,但不更新 [英] MongoDB atomic "findOrCreate": findOne, insert if nonexistent, but do not update
问题描述
如标题所示,我想通过_id对文档执行查找(一个),如果不存在,则创建它,然后查找它是否被创建,是否在回调中返回它
as the title says, I want to perform a find (one) for a document, by _id, and if doesn't exist, have it created, then whether it was found or was created, have it returned in the callback.
我不想更新它(如果存在的话),就像我读过的findAndModify一样.我在Stackoverflow上看到了许多其他与此相关的问题,但再次,我不想更新任何内容.
I don't want to update it if it exists, as I've read findAndModify does. I have seen many other questions on Stackoverflow regarding this but again, don't wish to update anything.
我不确定是否通过创建(不存在)实际上是每个人都在谈论的更新,这一切都令人困惑:(
I am unsure if by creating (of not existing), THAT is actually the update everyone is talking about, it's all so confuzzling :(
推荐答案
从MongoDB 2.4开始,对于像findOrCreate
这样的原子操作,不再需要依赖唯一索引(或任何其他解决方法).
Beginning with MongoDB 2.4, it's no longer necessary to rely on a unique index (or any other workaround) for atomic findOrCreate
like operations.
这要感谢2.4新增的 $setOnInsert
运算符.允许您指定仅在插入文档时发生的更新.
This is thanks to the $setOnInsert
operator new to 2.4, which allows you to specify updates which should only happen when inserting documents.
这与upsert
选项结合使用,意味着您可以使用findAndModify
来实现类似于findOrCreate
的原子操作.
This, combined with the upsert
option, means you can use findAndModify
to achieve an atomic findOrCreate
-like operation.
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向上插入一个文档,然后执行仅插入集.在这两种情况下,文档都会被退回.
As $setOnInsert
only affects documents being inserted, if an existing document is found, no modification will occur. If no document exists, it will upsert one with the specified _id, then perform the insert only set. In both cases, the document is returned.
这篇关于MongoDB原子"findOrCreate":findOne,如果不存在则插入,但不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!