0

I'm trying to segment user purchases in "periods". A new period begins when there are no purchases in the last 15 days.

For example, if user purchased on:

January 1
January 17
January 20
February 1
February 20

Segmentation in periods will be:

Period 1: { January 1 }
Period 2: { January 17, January 20, February 1 }
Period 3: { February 20 }

So, for each document like this in the collection:

{
  purchases: [
    {
      product: "1",
      date: ISODate('2019-01-01T00:00:00.000Z')
    },
    {
      product: "2",
      date: ISODate('2019-01-17T00:00:00.000Z')
    },
    {
      product: "3",
      date: ISODate('2019-01-20T00:00:00.000Z')
    },
    {
      product: "4",
      date: ISODate('2019-02-01T00:00:00.000Z')
    },
    {
      product: "5",
      date: ISODate('2019-02-20T00:00:00.000Z')
    }
  ]
}

I want to split it in:

{
  periods: [
    {
       products: [
         {
           product: "1",
           date: ISODate('2019-01-01T00:00:00.000Z')
         }
       ]
    },
    {
       products: [
         {
           product: "2",
           date: ISODate('2019-01-17T00:00:00.000Z')
         },
         {
           product: "3",
           date: ISODate('2019-01-20T00:00:00.000Z')
         },
         {
           product: "4",
           date: ISODate('2019-02-01T00:00:00.000Z')
         },
       ]
    },
    {
       products: [
         {
           product: "5",
           date: ISODate('2019-02-20T00:00:00.000Z')
         }
       ]
    }
}

I read the documentation of the aggregation framework, especially $bucket, but it seems to work only with fixed intervals.

italktothewind
  • 1,950
  • 2
  • 28
  • 55
  • [**MongoPlayground**](https://mongoplayground.net/p/K88xPwRDvAT) – Ashh Nov 15 '19 at 05:39
  • Hi @Ashh. I am sorry, but is not the same case. My first period does not begin with the first day of the year, but with the date of the first purchase. Also, periods in my case are not lasting always 15 days. If a user is buying things all the days, a period can last for years. The example shows clearly this edge cases. Thanks. – italktothewind Nov 19 '19 at 04:11

0 Answers0