'Mongodb aggregate get the expired records by using the epoch current timestamp
{
"id" : "58",
"topicHeader" : {
"replayData" : {
"messageDateInms" : NumberLong(1649448201357),
"messageDelayInms" : NumberLong(600000)
}
},
"status" : "IN_PROGRESS"
},
{
"id" : "59",
"topicHeader" : {
"replayData" : {
"messageDateInms" : NumberLong(1650220023677),
"messageDelayInms" : NumberLong(600000)
}
},
"status" : "IN_IROGRESS"
}
i need to get the expired records based on current epoch timestamp i.e.
(topicHeader.replayData.messageDateInms + topicHeader.replayData.messageDelayInms) <= epoch current timestamp
I am able to resolve by using find() but trying to find better solution so it wont cause any performance issue:
db.getCollection("col1").find
({
$expr: {
$lte: [{ "$add": ["$topicHeader.replayData.messageDateInms", "$topicHeader.replayData.messageDelayInms"] }, 1650226443611]
}
})
Thank you in advance.
Solution 1:[1]
Use $add to sum up the 2 fields. Use $toDate to cast them into date field and compare with $$NOW
db.collection.aggregate([
{
"$match": {
$expr: {
$lte: [
{
$toDate: {
"$add": [
"$topicHeader.replayData.messageDateInms",
"$topicHeader.replayData.messageDelayInms"
]
}
},
"$$NOW"
]
}
}
}
])
Here is the Mongo playground for your reference.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ray |
