upsert 脚本不工作

upsert script is not working

我正在尝试让 upsert 工作但没有结果

我在此脚本之前发布了三个变量。如果我更新,我会得到结果,但我想更新插入但没有得到结果。

这是我的代码:

if(isset($_POST)){
    if($array){
        $doc = $collection->update(
            array(
                '$set' => array(
                    '_id' => new MongoId(),
                    'organization' => $mysql_org_name,
                    'purch_code' => $mysql_purch_code,
                    'contentname' => $mysql_order_item_name,
                    array('upsert' => true)
                )
            )
        );
    }
}

您在单引号上设置了变量 $set '$set' => 数组(

Update expects 3 argument arrays。你只通过了一个。

首先,您将选项作为 $set 数组的一部分包含在内。它们应该在更新子句之后作为单独的参数传递。

此外,您没有匹配条件(即 select 要更新哪些项目的查询语句)。使用 upsert 和 $set 时,将使用两个数组 (see the relevant documentation).

中的字段创建一个新项目

最后,如果您没有为 _id 指定一个值,Mongo 将为您生成一个值。


例如,如果您想根据 organization 字段进行匹配:

if(isset($_POST)){
    if($array){
        $doc = $collection->update(
            array('organization' => $mysql_org_name),
            array(
                '$set' => array(
                    'purch_code' => $mysql_purch_code,
                    'contentname' => $mysql_order_item_name,
                )
            ),
            array('upsert' => true)
        );
    }
}

如果这匹配一个或多个条目,只有 purch_codecontentname 字段将在第一个匹配对象上更新(要更新多个条目,您必须指定 'multiple'=>true 在你的选项数组中)。如果没有匹配项,将插入一个新条目:

  1. 一个生成_id
  2. 所有匹配条件值(即 organization
  3. 所有更新运算符值(即 purch_codecontentname