2

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..

enter image description here

Maybe someone can help me figure where I'm going wrong!

1
  • I know of one solution so far .i.e offloading the merge in php using array_merge() and then rewrite the "coordinates" with $set. But this doesn't seem like the best solution to me. Commented Jul 27, 2015 at 20:14

1 Answer 1

2

You need to use the $each operator

$update = array('$push' => array("coordinates" => array('$each' => $events)));
$return = $collection->update($conditions, $update, $options)
Sign up to request clarification or add additional context in comments.

4 Comments

Ahh!! .. So that was what I was missing! Thanks a ton! :)
@ShalomSam Glad to have been of help!
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()
Using array_merge() is more expensive because $each appends each element to your array and is a native API so faster.

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.