FuelPHP updating embedded array documents in mongoDB
For some reason this was a DOOZY of problem. And it's because i didn't thoroughly read MongoDB's documentation!!!! They have it right there... The $ Positional operator is your friend! You should read mongodb's documentation page. But since you're already here, let's take a look at a very simple example using FuelPHP. Let's assume your schema looks like this. You are tracking anytime somebody clicks on a users links in their profile.
{ username:"jim", email:"[email protected]", links: [ {url:"http://www.73ro.com", visits:0}, {url:"http://flavors.me/jimmers", visits:3} ] }
I like to query the data first, to make sure we have a row to update. I don't use an upsert here, because the mongoDB documentation (yea, i read that in there this time) states that if it does not exist, it will insert a field name containing the '$' sign.
//Somehwere in our controller we have a function like this ... public static function click_link($url) { $mongodb = \Mongo_Db::instance('default'); $result = $mongodb->where(array('username'=>"jim", 'links.url'=>$url))->get_one('Links'); if($result) { $mongodb->where(array('username'=>"jim", 'links.url'=>$url]))->update('Links', array('$inc'=> array('links.$.count'=> 1)), array(), true); } }
the first lines should be familiar to you. Choosing the instance, then finding a row in the DB. The thing that might seem strange is the "links.url" part. Well you can use the dot notation to dig deeper into embedded objects. So I could go as deep as i needed if I had to (comments.author.firstname...) if i had to go deeper. the tricky noise, and what was causing me headache, was when you do an update, you can't just use the dot notation. You have to throw a dollar sign in between, so i did 'links.$.count', then it knew in the scope of this document where to update the count. This was a basic instruction, if you don't understand it read over the documentation at mongoDB. If it's still eluding you feel free to message me, i'd be glad to help, as it caused me a night of frustration. I finally found the mongodb google groups and it lead me to the solution. Great place, check it out if you haven't











