0

I am trying to learn MongoDB with PHP. I can successfully save a new document with ->save($object). My goal is to add a subdocument to a document with a specific _id.

I have a document:

"5197f4bef045a1d710000032": {
"_id": {
  "$id": "5197f4bef045a1d710000032"
},
"tag": 5487,
"serial": "1z5589ss56",
"type": "Soda Can",
"dept": "NOC",
"location": "Mitchell",
"date": 1368913086,
"moves": null
}

I would like to insert a new document into "moves".

I have been able to once with $set, however subsequent $push does nothing.

    <?php


$m = new Mongo();

$d = $m->selectDB('peeps');
$c = $d->family;
$fields = array('tag' => 5487 , 'serial' => '1z5589ss56', 'type' => 'Soda Can', 'dept' => 'NOC', 'location' => 'Mitchell', 'date' => time() );

$can = new Asset($fields);
#$c->save($can);

#Update to insert move

$c->update(array('_id' => new MongoID('5197f0cef045a1d710000032')), array('$push' => array('moves' => $can)));


$cur = $c->find();
$J = json_encode(iterator_to_array($cur));
print($J);


class Asset{

    public $tag;
    public $serial;
    public $type;
    public $dept;
    public $location;
    public $date;
    public $moves;

    public function __construct($fields){
        $this->tag = $fields['tag'];
        $this->serial = $fields['serial'];
        $this->type = $fields['type'];
        $this->dept = $fields['dept'];
        $this->location = $fields['location'];
        $this->date = $fields['date'];
    }
}

Based on what I have read, this should create a nested document inside 5197f0cef045a1d710000032.moves every time I reload the page.

I am not sure what I am missing.

Thanks,

Mitchell

1 Answer 1

2

You should not be using $set with a simple value if you plan on later using $push to the same field.

Use $push the first time you update also. It will create an array of a single element, and then you will be able to add (push) more elements to it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this, I am not sure why I was unable to find the tree in the forest. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.