0

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?

1 Answer 1

2

Use this one:

{
   $match: {
      $expr: {
         $gt: ["$createdDate", {
            $dateSubtract: {
               startDate: "$$NOW",
               unit: "day",
               amount: 2
            }
         }]
      }
   }
}
   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.