Home > Back-end >  Creating View in MongoDB
Creating View in MongoDB

Time:09-22

I'm trying to create a view in MongoDB which selects only the last 2 days worth of documents.

db.createView(
  "coll2DaysView",
  "coll",
  [{
    $match: {
      "createdDate":{
        $gt: new Date(new Date() - 2*24*3600000)
      }
    }
  }]
);

The standalone query works correctly, but when I create the view, it calculates date at the time of creation and doesn't update it every time I query the view.

This is how the view looks like,

db.getCollectionInfos({"type":"view"});

[
    {
        "name" : "coll2DaysView",
        "type" : "view",
        "options" : {
            "viewOn" : "coll",
            "pipeline" : [ 
                {
                    "$match" : {
                        "createdDate" : {
                            "$gt" : ISODate("2022-09-18T06:00:25.585-06:30")
                        }
                    }
                }
            ]
        },
        "info" : {
            "readOnly" : true
        }
    }
]

How can I make the view query only the last 2 days worth of data?

CodePudding user response:

Use this one:

{
   $match: {
      $expr: {
         $gt: ["$createdDate", {
            $dateSubtract: {
               startDate: "$$NOW",
               unit: "day",
               amount: 2
            }
         }]
      }
   }
}
   
  • Related