Dennis
Dennis

Reputation: 79

upsert script is not working

I'm trying to get upsert to work and getting no results

I have three variables I'm posting before this script. If I update, I get result, but I want to upsert and am getting no results.

Here is my code:

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)
                )
            )
        );
    }
}

Upvotes: 1

Views: 94

Answers (2)

cyfur01
cyfur01

Reputation: 3312

Update expects 3 argument arrays. You've only passed one.

First, you've included you options as part of the $set array. They should be passed as a separate argument after the update clause.

Also, you don't have a match criteria (i.e., a query statement to select which item(s) to update). When using upsert and $set, a new item would be created with the fields from both arrays(see the relevant documentation).

Finally, if you don't specify a value for _id, Mongo will generate one for you.


If, for instance, you wanted to match based on the organization field:

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)
        );
    }
}

If this matches one or more entries, only the purch_code and contentname fields will be updated on the first matching object (to update multiple entries, you'd have to specify 'multiple'=>true in your options array). If nothing matches, a new entry would be inserted with:

  1. A generated _id
  2. All of the match criteria values (i.e., organization)
  3. All of the update operator values (i.e., purch_code and contentname)

Upvotes: 1

mrTall
mrTall

Reputation: 51

You have variable $set on single quote '$set' => array(

Upvotes: 1

Related Questions