Search code examples
mongodbaggregate

mongodb aggregate get current date


I'm using metabase and I have native mongodb query. I want to filter documents created yesterday. The problem is that I only have json. Is there any way to compute yesterday?

my json is:

[...
{
    "$match": {
      "createdAt": { "$ne": "$yesterday" },
    }
},
...]

Solution

  • Unfortunately Metabase does not allow to use Date() to get now Date. also you should notice that dateFromString is available in version 3.6 of mongoDB and newer but another problem here is i think dateFromString does not work well with now Date in aggregate and mongoDB return an error that you should pass a string to convert to Date in dateFromString! so i suggest to you to get yesterday Date in metabase write code something like this :

    [{
      "$project": {
          "user": 1,
          "createdAt": 1,
          "yesterday": {
              "$subtract": [ISODate(), 86400000]
          }
      }
    },
    {
     "$project": {
         "user": 1,
         "yesterday": 1,
         "createdAt": 1,
         "dateComp": { "$cmp": ["$yesterday", "$createdAt"] }
     }
    },
    {
    "$match": { 
         "dateComp": -1 
    }}]