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

1

In the collection documents lightningStrikes there is a datetime property whose value is of type ISODate. There are several new documents in this collection every minute.

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

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

For this 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 new Date() objects were interpreted at creation time, setting a date as a condition of my view, as seen when rotating:

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 for these new Date() objects to be interpreted at the time of my query , when I make a find in the view, not at the time of creating it. >

I think 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)
                }
            }
        }
    ]
}

Does anyone have any ideas? Thank you!

    
asked by anonymous 28.09.2017 / 21:57

0 answers