MongoDB atomic“findOrCreate":findOne,如果不存在则插入,但不更新 [英] MongoDB atomic "findOrCreate": findOne, insert if nonexistent, but do not update

查看:21
本文介绍了MongoDB atomic“findOrCreate":findOne,如果不存在则插入,但不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我想通过_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.

这要感谢 $setOnInsert 运算符 2.4 的新功能,允许您指定仅在插入文档时才发生的更新.

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 atomic“findOrCreate":findOne,如果不存在则插入,但不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆