I've seen a bunch of the other Mongo PHP $push questions up here on SO, but for some reason none of what they're saying is working, so I'm posting my own version.
Basically, I'm trying to follow a guideline set by 10gen where representing something like a news feed or blog/comment post should be done using buckets - making documents that hold a certain number (50) of events (comments, etc.), and then creating multiple documents as the content grows.
What I'm trying to do is push documents ($event
) into an array (events
), but there seems to be some confusion with PHP when the document doesn't exist (upserting). I tried to do it with an insert, but insert and $push
don't play well together.
Here's what I have right now:
$historyDoc = array('_id'=>$uID, 'count'=>1,
array('$push' => array('events' => $event)));
$query = array('_id'=>$uID);
//add user to history
$collection->update($query,$historyDoc,
array('safe'=>true,'timeout'=>5000,'upsert'=>true));
Where $event
is a properly-formatted array (document) of things (e.g. timestamp, userID, action, name) and $uID
is a MongoID object taken from another collection.
The result that I get is this:
{
"_id": {
"$oid": "4f77ec39fef97a3965000000"
},
"0": {
"$push": {
"events": {
"timestamp": 1333259321,
"action": "achievement",
"pts": 0,
"name": "join"
}
}
},
"count": 1
}
Which is good, because my document is at least showing up right, but how the hell is there a key with a "$" in it? It's not like I'm failing to escape the $
...I've been very intently using single quotes for that exact reason.
Maybe there's something I'm missing, or maybe I broke PHP, but I've been wrestling with this one for awhile and there's nothing I can thing of. It's holding my whole project up, so....>:/