I am trying to create a view for records created/modified in last 24 hours. Is it possible?
Tried creating view as below
db.createView(
"viewname",
"sourcecollection",
[ { $match: {"modifiedTime":{$gte:new Date(Date.now() - 24*60*60*1000), $lte:new Date()}}}]
)
But it translates to static values
{
modifiedTime: {
$gte: ISODate('2022-10-25T23:20:21.602Z'),
$lte: ISODate('2022-10-26T23:20:21.602Z')
}
}
Did read about $$NOW but could not get it working in create view command. Please suggest
CodePudding user response:
Try this one:
db.createView(
"viewname",
"sourcecollection",
[
{
$match: {
$expr: {
$and: [
{ $gte: ["$modifiedTime", { $dateSubtract: { startDate: "$$NOW", unit: "day", amount: 1 } }] },
{ $lte: ["$modifiedTime", "$$NOW"] }
]
}
}
}
]
)
CodePudding user response:
Based on above post, got it working in Mongo 4.4 with below command. Dynamic view for records in last 24 hours.
db.createView(
"viewname",
"source",
[ { $match: {$expr: { $gte: [ "modifiedTime" , { $subtract: [ "$$NOW", 24*60*60*1000 ] } ] }}}]
)