0

MongoDB Document structure is as follows:

{
    "_id" : ObjectId("5755dbcf725c4a1394f5d64f"),
    "date_prices" : [ 
        {
            "d" : ISODate("2016-06-06T20:23:32.184Z"),
            "p" : 895000
        }, 
        {
            "d" : ISODate("2016-06-10T05:49:25.362Z"),
            "p" : 895000
        }, 
        {
            "d" : ISODate("2016-06-17T22:58:14.002Z"),
            "p" : 895000
        }, 
        {
            "d" : ISODate("2016-06-19T19:46:35.826Z"),
            "p" : 895000
        }
    ],
    "id" : "6315590",
}

We need to find all documents where the first entry of date_prices array (index 0 thus) has a date greater than a specific value and where the last array entry (index 3 in the example above) has a date lower than a specific value.

Any hint on how to do this in PHP would be greatly appreciated.

Note: date_prices array typically contains hundreds of entries.

Many thanks, Tom

UPDATE:

After some further searching I came up with the following request (PHP) but it isn't working - any hint would be appreciated, thx!

array(1) { ["date_prices.0.d"]=> array(1) { ["$gte"]=> string(10) "2011-08-01" } }
Tom
  • 1,375
  • 3
  • 24
  • 45
  • This answer will help you to select the last entry of date_prices: http://stackoverflow.com/questions/21952005/using-slice-operator-to-get-last-element-of-array-in-mongodb/21952273#21952273 – Bert Aug 04 '16 at 20:46
  • To select a date, you need to use `MongoDate`: `['date_prices.0.d' => ['$gte' => new MongoDate(strtotime('2011-08-01'))]]` – Bert Aug 04 '16 at 20:47
  • Thx. Unfortunately I get a "Fatal error: Class 'MongoDate' not found" while var_dump(extension_loaded('mongodb')) return "true". Any idea what this could be? – Tom Aug 04 '16 at 20:51
  • Try `MongoDB\BSON\UTCDateTime()` instead if you're using PHP7 – Bert Aug 04 '16 at 20:56
  • Thx, no compilation error anymore. I get the following query but it doesn't filter results (even older entries are returned): array(1) { ["date_prices.0.d"]=> array(1) { ["$gte"]=> object(MongoDB\BSON\UTCDateTime)#4 (1) { ["milliseconds"]=> string(10) "1467928800" } } – Tom Aug 04 '16 at 21:04
  • Found the problem: UTCDateTime expects miliseconds while strtotime() returns seconds. I had thus to multiply by 1000. Thx – Tom Aug 05 '16 at 07:56

0 Answers0