XQuery returns items not in set


I am writing some XQuery on the following document:

      <content yearID="1998">
         <month monthID="1">
         <month monthID="2">

I want to query the document for a given year and month and have it return the entire node with just that month (no other months included). My XQuery is as follows:

for $x in doc("alcala/ledger.xml")//pages/page
where $x/content[@yearID="1998"] and $x/content/month[@monthID="2"] 
return $x

My result is giving me both months 1 and 2. If I search for monthID=“3”, I get months 2 and 3. I’ve tried just a search on the month (without the year filter) and I get the same results. Why is it giving me part of the previous month along with the month I want? How do I remove the month I do not want?


For those interested in the answer, I had my question answered on Stackoverflow (link here: [https://stackoverflow.com/questions/49960730/xquery-returns-items-not-in-set/49963753#49963753](StackOverflow: XQuery returns items not in set)). I’ll post the answer below here as well.

The problem was in my return statement. I needed to specify in the return to only return items within the content node that were related to my search. Here’s the revised xquery:

for $x in /pages/page
where $x/content[@yearID="1998"] and $x/content/month[@monthID="2"]
        $x/content[@yearID = 1998]
            @*, month[@monthID = 2]
                !<month>{@*, node()}</month>