Mongodb – Expand a date range in mongodb

mongodbnosql

I have a document structure like

{
  "startDate": ISODate("2015-01-01T00:00:00Z"),
  "endDate" : ISODate("2015-01-10T00:00:00Z"),
  "foo" : "bar"
}

Is it possible to expand the date range like this?

{
 "dates": [
           ISODate("2015-01-01T00:00:00Z"),
           ISODate("2015-01-02T00:00:00Z"),
           ISODate("2015-01-03T00:00:00Z"),
           ISODate("2015-01-04T00:00:00Z"),
           ISODate("2015-01-05T00:00:00Z"),
           ISODate("2015-01-06T00:00:00Z"),
           ISODate("2015-01-07T00:00:00Z"),
           ISODate("2015-01-08T00:00:00Z"),
           ISODate("2015-01-09T00:00:00Z"),
           ISODate("2015-01-10T00:00:00Z")
        ]
}

Best Answer

You may need to elaborate on this a bit more but yes it is possible to store that data as you've described it. Here's an example, using your document model, of such an array of dates in a document in a collection. Personally, I would look at modifying this as I've described at the end but of course it all depends on what your queries need to do with the data.

{
"_id" : ObjectId("55474c322e8f6b5a9dda1a0f"),
"dates" : [ 
    ISODate("2015-01-01T00:00:00.000Z"), 
    ISODate("2015-01-02T00:00:00.000Z"), 
    ISODate("2015-01-03T00:00:00.000Z"), 
    ISODate("2015-01-04T00:00:00.000Z"), 
    ISODate("2015-01-05T00:00:00.000Z"), 
    ISODate("2015-01-06T00:00:00.000Z"), 
    ISODate("2015-01-07T00:00:00.000Z"), 
    ISODate("2015-01-08T00:00:00.000Z"), 
    ISODate("2015-01-09T00:00:00.000Z"), 
    ISODate("2015-01-10T00:00:00.000Z")
]
}

Are you perhaps asking "how" to actually do so or how to work with them? Pending what your use case is, you may want to alter that document model and opt for a different approach than a pure array of dates. I may instead use an array of subdocuments as shown in this example and I've included an example of a query that retrieves an element as well. Multiple people could, and likely will herein, suggest doing this in different ways, without more clarity regarding the use case.

//Example using subdocs
{
"_id" : ObjectId("55474e332e8f6b5a9dda1a10"),
"dates" : [ 
    {
        "date" : ISODate("2015-01-01T00:00:00.000Z")
    }, 
    {
        "date" : ISODate("2015-01-02T00:00:00.000Z")
    },  
... etc

  //using embedded docs
  db.rangeTest.find(
 {'dates.date': {$gte:ISODate("2015-01-08T00:00:00.000Z"), $lte:ISODate("2015-01-09T00:00:00.000Z")}},
{_id:0, 'dates.$':1} )