user3636924
user3636924

Reputation: 131

Xquery in Marklogic to return datetime less than 1 month from the current date

Delete documents less than 30 days in Marklogic Xquery

I was searching over the internet to find how to return documents less than 1 month old from the current date and i found the above link. Since there are no range indexes for the element i am using

let $currentdt := fn:current-dateTime()
let $amonthAgo := $currentdt- xs:yearMonthDuration("P1M")
cts:search(doc(), 
  cts:element-query(xs:QName("myDateTimeField"), cts:true-query())
)[.//myDateTimeField[xs:dateTime(.) eq $amonthAgo]]

returns nothing.


I have sample values such as

2021-05-18T06:32:34.761729-04:00
2021-05-15T06:32:34.761729-04:00
2021-03-19T06:32:34.761729-04:00
2021-06-15T06:32:34.761729-04:00

TIA!

Upvotes: 2

Views: 250

Answers (1)

Leo Wörteler
Leo Wörteler

Reputation: 4241

Aside from a missing return for the FLWOR expression, you are asking for all matches that are exactly one month old, because you are using eq in the comparison. If you want to find documents that are younger than one month, you want their date to be after the point in time exactly one month ago (i.e., $amonthAgo). You can correct and simplify the predicate to xs:dateTime(myDateTimeField) gt $amonthAgo. Here is a stand-alone example that works for me:

declare context item := document {
  <doc>
    <e id="1">
      <myDateTimeField>2021-05-18T06:32:34.761729-04:00</myDateTimeField>
    </e>
    <e id="2">
      <myDateTimeField>2021-05-15T06:32:34.761729-04:00</myDateTimeField>
    </e>
    <e id="3">
      <myDateTimeField>2021-03-19T06:32:34.761729-04:00</myDateTimeField>
    </e>
    <e id="4">
      <myDateTimeField>2021-06-15T06:32:34.761729-04:00</myDateTimeField>
    </e>
  </doc>
};
let $currentdt := fn:current-dateTime()
let $amonthAgo := $currentdt - xs:yearMonthDuration("P1M")
return //e[xs:dateTime(myDateTimeField) gt $amonthAgo]

Result (on 2021-06-19):

<e id="4">
  <myDateTimeField>2021-06-15T06:32:34.761729-04:00</myDateTimeField>
</e>

Upvotes: 2

Related Questions