0

How can I used the mongodb component "find documents" to get the last 24 hours data from collection?

I tried the following query in the component but it didn't work.

Sample:

"createdAt" :  { $gte: new Date(new Date().getTime() - 86400000) }

How I can get the last data (24 hours) from mongo?

1
  • Please share the XML for the full operation. Also, what exactly didn't work? If there is an error or results please share.
    – aled
    Commented Oct 19, 2022 at 10:13

1 Answer 1

0

I'm guessing that you are trying to use Java or MEL syntax in Mule 4 to construct the JSON that is used for the MongoDB query. In Mule 4 you need to use DataWeave as the expression language. An expression in DataWeave to generate something similar could be:

%dw 2.0
output application/json
---
{
    "createdAt" :  { 
        "\$gte": (now() - |P1D|) as String { format: "yyyy-MM-dd'T'hh:mm:ss'Z'"}
    }
}

Output:

{
  "createdAt": {
    "$gte": "2022-10-18T12:06:19Z"
  }
}

If you need a different date time format you can tinker with the format in the expression.

Note that DataWeave supports date arithmetic with periods of time so you don't need to use hacks like subtracting a number of milliseconds. |P1D| is a period of 1 day.

1
  • This answers uses Mule expressions. If you are trying to use pure MongoDB features you need a different solution.
    – aled
    Commented Oct 19, 2022 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.