Note that there are some explanatory texts on larger screens.

plurals
  1. POWorking with nested documents/arrays in Lithium and MongoDB
    text
    copied!<p>I'm new to both MongoDB and Lithium and I can't really find the "good way" of working with nested documents. I noticed that when I try</p> <pre><code>$user = Users::find('first' ... ); $user-&gt;somenewfield = array('key' =&gt; 'val'); </code></pre> <p>what I get for "somenewfield" is a Document object. But there is also a DocumentArray class - what is the difference between them? </p> <p>When I call </p> <pre><code>$user-&gt;save(); </code></pre> <p>this results in Mongo (as expected):</p> <pre><code>"somenewfield" : { "key": "value" } </code></pre> <p>OK, but when I later want to add a new key-value to the array and try</p> <pre><code>$user-&gt;somenewfield['newkey'] = 'newval'; var_dump($user-&gt;somenewfield-&gt;to('array')); // shows the old and the new key-value pairs $user-&gt;save(); // does not work - the new pair is not added </code></pre> <p>What is the correct way to adding a new array to a document using lithium? What is the correct way of updating the array/adding new values to the array? Shall I alywas give a key for the array value? </p> <p>Thanks for the help in advance. I'm kinda stuck ... reading the documentation, reading the code ... but at some points it gets difficult to find out everything alone :)</p> <p>Edit: What I found at the end was that the way I shall use nested arrays is with $push and $pull:</p> <pre><code>Users::update(array('$push' =&gt; array('games' =&gt; (string) $game-&gt;_id)), array( '_id' =&gt; $this-&gt;user()-&gt;_id, 'games' =&gt; array('$ne' =&gt; (string) $game-&gt;_id)), array('atomic' =&gt; false)); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload