Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB:执行原子创建和返回操作_Mongodb - Fatal编程技术网

MongoDB:执行原子创建和返回操作

MongoDB:执行原子创建和返回操作,mongodb,Mongodb,我需要在mongodb中创建一个文档,然后立即希望它在我的应用程序中可用。通常的方法是(在Python代码中): 这有两个问题: 对服务器的两个请求 不是原子的 因此,我尝试使用find\u和\u modify操作,在upserts的帮助下有效地执行“创建并返回”,如下所示: doc = collection.find_and_modify( # so that no doc can be found query= { '__no_field__':'__no_value__

我需要在mongodb中创建一个文档,然后立即希望它在我的应用程序中可用。通常的方法是(在Python代码中):

这有两个问题:

  • 对服务器的两个请求
  • 不是原子的
因此,我尝试使用
find\u和\u modify
操作,在
upserts
的帮助下有效地执行“创建并返回”,如下所示:

doc = collection.find_and_modify(
    # so that no doc can be found
    query= { '__no_field__':'__no_value__'},

    # If the <update> argument contains only field and value pairs,
    # and no $set or $unset, the method REPLACES the existing document
    # with the document in the <update> argument,
    # except for the _id field
    document= {'name':'mike', 'email':'mike@gmail.com'},

    # since the document does not exist, this will create it
    upsert= True,

    #this will return the updated (in our case, newly created) document
    new= True
)
doc=collection.find\u和\u modify(
#这样就找不到文件了
查询={'\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,
#如果参数仅包含字段和值对,
#如果没有$set或$unset,则该方法将替换现有文档
#在论点中的文件,
#除了_id字段
文件={'name':'mike','email':'mike@gmail.com'},
#由于该文档不存在,因此将创建它
upsert=True,
#这将返回更新的(在我们的例子中是新创建的)文档
新=真
)

这确实如预期的那样有效。我的问题是:这是否是完成“创建并返回”的正确方法,还是我缺少了什么问题?

普通的常规insert调用到底缺少什么

如果不知道_id是什么,您可以先自己创建_id并插入文档。那你就知道它会是什么样子了。其他字段都不会与发送到数据库的字段不同


如果您担心插入成功的保证,您可以检查返回代码,并设置一个提供足够保证(例如它已刷新到磁盘或复制到足够多的节点)。

如果我不传递_id,它是由mongo客户端还是在服务器上创建的?因为如果客户端创建了_id,那么我可能不会从
查找和修改
中得到任何东西,。我以为我是服务器创建了缺失的_id,我想客户端驱动程序创建了_id(至少在Java中是这样),但是谁创建了它有什么区别吗?可能没有。我只是有点担心自己插入的文档与数据库返回的文档完全相同,因此从数据库中获得一份原始副本会让我感觉更舒服一些。但我想你是对的。只要确保你使用你的驱动程序的官方ObjectId类。这应该行得通。
doc = collection.find_and_modify(
    # so that no doc can be found
    query= { '__no_field__':'__no_value__'},

    # If the <update> argument contains only field and value pairs,
    # and no $set or $unset, the method REPLACES the existing document
    # with the document in the <update> argument,
    # except for the _id field
    document= {'name':'mike', 'email':'mike@gmail.com'},

    # since the document does not exist, this will create it
    upsert= True,

    #this will return the updated (in our case, newly created) document
    new= True
)