MongoDB PHP insert into sub-array

776 Views Asked by At

Ok, not sure if mongodb can do this, but what I need is for the following JSON to be inserted into my currency DB.

The part we want to update is exchangehistory, we need to keep all the history of the exchange rates for that day. and the next day e.g.

for e.g

{"from":"USD","currentexchange":[{"to":"NZD","rate":"1.3194","updated":"6\/5\/20121:38am"},{"to":"KWD","rate":"0.2807","updated":"6\/5\/20121:38am"},{"to":"GBP","rate":"0.6495","updated":"6\/5\/20121:38am"},{"to":"AUD","rate":"1.0228","updated":"6\/5\/20121:38am"}],"exchangehistory":{"6\/5\/2012":[{"1:38am":[{"to":"NZD","rate":"1.3194","updated":"1:38am"}]},{"1:38am":[{"to":"KWD","rate":"0.2807","updated":"1:38am"}]},{"1:38am":[{"to":"GBP","rate":"0.6495","updated":"1:38am"}]},{"1:38am":[{"to":"AUD","rate":"1.0228","updated":"1:38am"}]}]}}
2

There are 2 best solutions below

2
On BEST ANSWER

I would very likely not store this in an array like this. I would create a flat data structure that has:

{
    from: "USD",
    to: "EUR",
    updated: new DateTime("2012-05-04 13:43"),
    rate: 1.235,
},
{
    from: "USD",
    to: "EUR",
    updated: new DateTime("2012-05-06 13:43"),
    rate: 1.24,
},
{
    from: "USD",
    to: "AUD",
    updated: new DateTime("2012-05-06 13:43"),
    rate: 1.43,
}

This is a lot lighter on the database, as documents never grow. And if documents grow they have to be moved. You can also very easily query the current rate:

$collection->find( array( 'from' => 'USD', 'to' => 'EUR' ) )
           ->sort( 'updated' => -1 )->limit( 1 );

And accessing all historical information:

$collection->find( array( 'from' => 'USD', 'to' => 'EUR' ) )
           ->sort( 'updated' => -1 )->skip( 1 );
0
On

This is not for PHP but it may be useful. you have to make a BSON object from your json string in order to be stored in database. Creating BSON from JSON As well you can use MongoDB PHP Driver tutorial and docs. They can be found here : MongoDB PHP Driver Tutorial