1

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"}]}]}}
RussellHarrower
  • 6,470
  • 21
  • 102
  • 204
  • Look for $addToSet. Possible duplicate : http://stackoverflow.com/questions/7026483/insert-data-into-inner-array-in-mongodb – Justin T. Jun 05 '12 at 06:12

2 Answers2

0

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 );
Derick
  • 35,169
  • 5
  • 76
  • 99
  • while that works great, we also need to store the history of the currency rates – RussellHarrower Jun 05 '12 at 13:10
  • Right, you'd still have the old documents for each conversion. There is nothing that stops you from having two USD->EUR documents with a different 'updated' field. I've added another document above to make that clear. – Derick Jun 05 '12 at 13:57
-1

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

Community
  • 1
  • 1
Kamran Amini
  • 1,062
  • 8
  • 14