Home > database >  Mongodb aggregate get the expired records by using the epoch current timestamp
Mongodb aggregate get the expired records by using the epoch current timestamp

Time:04-18

    { 
      "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.

CodePudding user response:

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.

  • Related