How to retrieve data from the previous day without explicitly specifying a date?

Hi everyone!

I’m trying to create a query that gets the data from the previous day for automatization purposes. I’m writing this:

db.getCollection(“media”).aggregate([
{
“$addFields”: {
“today”: {
“$dateFromString”: {
“dateString”: {
“$dateToString”: {
“date”: “$$NOW”,
“format”: “%Y-%m-%dT%H:%M:%S%z”
}
}
}
}
}
},
{
“$addFields”: {
“yesterday”: {
“$dateFromString”: {
“dateString”: {
“$dateToString”: {
“date”: {
“$subtract”: [
“$$NOW”,
86400000 // Milliseconds in a day
]
},
“format”: “%Y-%m-%dT%H:%M:%S%z”
}
}
}
}
}
},
{
“$match”: {
“dateAdded”: {
“$gte”: “$yesterday”,
“$lt”: “$today”
}
}
},
{
“$project”: {
“today”: 0,
“yesterday”: 0
}
}
])

However, I’m getting this error: Mongo Server error (MongoCommandException): Command failed with error 17276 (Location17276): ‘Use of undefined variable: NOW’ on server 20.114.50.151:27017.

The full response is:
{
“ok” : 0.0,
“errmsg” : “Use of undefined variable: NOW”,
“code” : 17276.0,
“codeName” : “Location17276”
}

It seems like my free version of Studio 3T does not support the “NOW” function. Does anybody have any idea how to achieve this?

Hey there! Sorry for the late reply on this!

I’ve just tried replicating the issue but your query runs fine on my MongoDB server. The $$NOW variable should be evaluated entirely by the server, Studio 3T doesn’t parse it at all.

Are you running a version older than 4.2? The $$NOW variable was only added in MongoDB 4.2: https://www.mongodb.com/docs/manual/reference/aggregation-variables/#mongodb-variable-variable.NOW

1 Like