I’m trying to find User
s who logged in the last day.
The userActivity
field is an object on User
. The userActivity
object contains a field called hourly
which is an array of dates. I want the find any users who’s hourly array contains a date greater than a day ago using aggregation.
User schema
{
userName:"Bob",
userActivity:
{"hourly":
[
"2022-05-09T02:31:12.062Z", // the user logged in
"2022-05-09T19:37:42.870Z" // saved as date object in the db
]
}
}
query that didn’t work
const oneDayAgo = new Date();
oneDayAgo.setDate(oneDayAgo.getDate() - 1);
const usersActiveToday = await User.aggregate([
{
$match: {
$expr: { $gt: [oneDayAgo, '$userActivity'] },
},
},
]);
If today is September 13, 11pm, I’d expect the results to the above to show users who had activity between the 12th and 13th.
Instead I am getting all users returned.
3
Answers
You can try something along these lines:
Here, we
$anyElementTrue
, to find if any element in the arrayhourly
, is greater than the day before, and store it as a boolean value in a new field. Then we filter the docs on the basis of that field using$match
.Here’s the playground link.
If you want to use an aggregation pipeline, then one option is to use
$max
to find if there are items that are greater thanoneDayAgo
:See how it works on the playground example – aggregation
But, you can also do it simply by using
find
:See how it works on the playground example – find
This can be considered as a 3 step process
max
)Working Code Snippet:
Here’s code in action: Mongo Playground