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"}]}]}}
1

2 Answers 2

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 );
Sign up to request clarification or add additional context in comments.

2 Comments

while that works great, we also need to store the history of the currency rates
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.
-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.