How to create a view whose filter is based on the date/time of the query?

Asked

Viewed 41 times

1

In the Collection documents lightningStrikes there is a property datetime, whose value is of type Isodate. Every minute several new documents enter this Center.

My goal is to create a view that always returns data from the last 20 minutes, as in the query:

db.lightningStrikes.find({ datetime: { $gte: new Date(new Date() - 1000*60*20) } })

For that I circled the following command:

db.createView(
    "latestLightningStrikes",
    "lightningStrikes",
    [
        { $match: { datetime: { $gte: new Date(new Date() - 1000*60*20) } } }
    ]
)

This command creates the view, but these objects new Date() were interpreted at the time of creation, setting a date as a condition of my view, as seen when running:

db.system.views.find().pretty()

{
    "_id" : "lightning.latestLightningStrikes",
    "viewOn" : "lightningStrikes",
    "pipeline" : [
        {
            "$match" : {
                "datetime" : {
                    "$gte" : ISODate("2017-09-28T19:25:34.410Z")
                }
            }
        }
    ]
}

What I need is these objects new Date() be interpreted at the time of my consultation, when I make a find in the view, and not at the time of its creation.

I believe this should be the result:

db.system.views.find().pretty()

{
    "_id" : "lightning.latestLightningStrikes",
    "viewOn" : "lightningStrikes",
    "pipeline" : [
        {
            "$match" : {
                "datetime" : {
                    "$gte" : new Date(new Date() - 1000*60*20)
                }
            }
        }
    ]
}

Anybody got any ideas? Thanks in advance!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.