I have this collection. I want to query entries so that either one of key "2" or "3" would be removed because the createdAt entries have a difference less than 1 hour. What would be the query?
CodePudding user response:
You can use $gt
query. See the document here
And here is a code example. Just change the places with your property, which is createdAt
in your scenario.
let user = await User.deleteMany({
createdAt: { $gt: Date.now() - 3600000 } // 3600000 means 1 hour in millisecond
});
// Rest of your code
CodePudding user response:
Query
- uses
$dateTrunc
with unit hour, that means keep the date as it is, but make zero all the left after the date - group by that trunc date => dates with same hour are in the same group
- keep only one of them
*query doesn't work with difference, it works by same hour, for example 1:01
is the same with 1:59
but 1:59
is not same group with 2:01
aggregate(
[{"$group":
{"_id":{"$dateTrunc":{"date":"$createdAt", "unit":"hour"}},
"doc":{"$first":"$$ROOT"}}},
{"$replaceRoot":{"newRoot":"$doc"}}])