MongoDB - help with a PHP query
I have the following object stored in a MongoDB:
[_id] => MongoId Object (
)
[horses] => Array (
[0] => Array (
[name] => Youve Been Mowed
[selectionId] => 3004097
)
[1] => Array (
[name] => Rascal In The Mix
[selectionId] => 3460932
)
[2] => Array (
[name] => Clumber Place
[selectionId] => 2986884
)
[3] => Array (
[name] => Pretty Orchid
[selectionId] => 2581717
)
[4] => Array (
[name] => Astrodonna
[selectionId] => 2568095
)
[5] => Array (
[name] => Just Sam
[selectionId] => 2511403
)
[6] => Array (
[name] => Many Welcomes
[selectionId] => 2866423
)
[7] => Array (
[name] => Two Turtle Doves
[selectionId] => 3857873
)
[8] => Array (
[name] => Piquante
[selectionId] => 3372813
)
[9] => Array (
[name] => Nimmys Special
[selectionId] => 3066557
)
)
[marketId] => 101531031
[marketName] => 7f Hcap
Now I want to add a new field:
[_id] => MongoId Object (
)
[horses] => Array (
[0] => Array (
[name] => Youve Been Mowed
[selectionId] => 3004097
[odds] => Array(
10000000 => 1.5
10000020 => 1.6
10000030 => 1.7
)
)
...
etc.
...
The 100000XX is a timestamp and the 1.X are the odds
I'm really开发者_StackOverflow中文版 banging my head off the desk here. Any suggestions much appreciated.
Here's what I have sofar (wrong):
foreach($horses as &$horse)
{
$newdata=array('$set'=>array($horse['odds']=>$price));
$filter=array("marketId"=>$marketId);
$c->update($filter,$newdata);
}
You need to use dot notation:
foreach($horses as &$horse)
{
$newdata=array('$set'=>array('horses.odds'=> array($horses['odds'] => $price)));
$filter=array("marketId"=> $marketId);
$c->update($filter,$newdata);
}
See http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29.
Thanks so much for your reply. Are you the Kristina from the MongoDB Perl module on CPAN? :)
Here's my working code:
$data_object=null;
for($i=0;$i<sizeof($horses);$i++)
{
$data_object->timestamp=$time;
$data_object->niceTime=date("c");
$data_object->price=$price;
$this_horse=$horses[$i];
if($this_horse['selectionId']==$horseId)
{
$newdata=array('$push'=>array("horses.$i.odds"=>$data_object));
$filter=array();
$options=array('upsert'=>true);
$c->update($filter,$newdata,$options);
}
}
精彩评论