sunny
sunny

Reputation: 3891

MongoDB with PHP driver - how to push onto multiple arrays with one update query?

I would like to push onto multiple arrays contained within the same document with a single MongoDB update query in PHP. I have tried the following two calls without success:

 //this one causes php run error
 $collection->update(array("scienceNumber"=>$scienceNumber),  array('$push'=>array(array("comments"=> $comment), array("ids"=> $userID), array("times"=> $time))), array("upsert"=>true));

 //this one runs a query but only pushes $time onto the times array, ignoring the other push instructions
 //that outcome totally makes sense since I am assigning all these different arrays to the same key...no complaints...but then the above didn't work either
 $collection->update(array("scienceNumber"=>$scienceNumber), array('$push'=>array("comments"=> $comment), '$push'=>array("ids"=> $userID), '$push'=>array("times"=> $time) ), array("upsert"=>true));

So how can this be done in one update query?

Also I realize I could do this by having an array of documents and storing the values all together, but that would make other queries more cumbersome later on.

Upvotes: 1

Views: 47

Answers (1)

Sede
Sede

Reputation: 61253

What about this:

$collection->update(
    array("scienceNumber"=>$scienceNumber),   
    array('$push'=>array("comments"=> $comment, "ids"=> $userID, "times"=> $time)),
    array("upsert"=>true)
);

Upvotes: 1

Related Questions