I'm trying to update the "coordinates" property in the Mongo document with new events. ie. Merge the "coordinates" array (contains array of events) with new array of events.
What I have so far :
$update = array('$push' => array("coordinates" => $events));
/** @var \MongoCollection $collection */
$collection = $db->$collectionName;
$return = $collection->update($conditions, $update, $options);
if ($return === false) {
throw new \ErrorException('Unable to update collection');
}
This works without throwing any error but not as intended. The above query appends the $events array to the "coordinates" array as an array.
Confusing? Maybe the image below will explain better..
Maybe someone can help me figure where I'm going wrong!
asked Jul 27, 2015 at 20:06
Shalom Sam
1,5591 gold badge17 silver badges28 bronze badges
1 Answer 1
You need to use the $each operator
$update = array('$push' => array("coordinates" => array('$each' => $events)));
$return = $collection->update($conditions, $update, $options)
answered Jul 27, 2015 at 21:11
Sede
61.5k20 gold badges159 silver badges162 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Shalom Sam
Ahh!! .. So that was what I was missing! Thanks a ton! :)
Sede
@ShalomSam Glad to have been of help!
Shalom Sam
just another question out of curiosity @user3100115 - does
$each actually run some sort of foreach loop inside mongodb? If so i wonder which is more expensive, $each or array_merge()Sede
Using
array_merge() is more expensive because $each appends each element to your array and is a native API so faster.default
array_merge()and then rewrite the"coordinates"with $set. But this doesn't seem like the best solution to me.