0

I have the following JSON file:

"spells": [
 {
  "spell":"Aberto",
  "effect":"opens objects",
  "_id":"5b74ebd5fb6fc0739646754c",
  "type":"Charm"
 },
 {
  "spell":"Accio",
  "effect":"Summons an object",
  "__v":0,
  "_id":"5b74ecfa3228320021ab622b",
  "type":"Charm"
 },
 {
  "spell":"Age Line",
  "effect":"Hides things from younger people",
  "__v":0,
  "_id":"5b74ed2f3228320021ab622c",
  "type":"Enchantment"
 },
 {
  "spell":"Aguamenti",
  "effect":"shoots water from wand",
  "__v":0,
  "_id":"5b74ed453228320021ab622d",
  "type":"Charm"
 },
 {
  "spell":"Alarte Ascendare",
  "effect":"shoots things high in the air",
  "__v":0,
  "_id":"5b74ed583228320021ab622e",
  "type":"Spell"
 }

}

Can you help me how to count all the spells with XQuery where the "type" = "Spell" and separately all the spells where the "Type"= "charm". The JSON file is much bigger, I just don't wanted to paste here the whole file. Thank you.

1 Answers1

0

It seems like a straight-forward grouping and counting then:

declare variable $spell-types as xs:string* external := ('Spell', 'Charm');

for $spell in ?spells?*[?type = $spell-types]
group by $t := $spell?type
return $t || ' : ' || count($spell)

https://xqueryfiddle.liberty-development.net/nc4P6y2

Or, as Michael Kay has pointed out, with a given sequence of values it suffices to use

for $spell-type in $spell-types
return $spell-type || ' : ' || count(?spells?*[?type = $spell-type])

https://xqueryfiddle.liberty-development.net/nc4P6y2/1

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • 1
    I'm not sure why the grouping is needed: `count(?spells?*[?type = 'Spell'])` – Michael Kay Jan 04 '20 at 21:59
  • @MichaelKay, right, somehow I started without any sequence of wanted types and only grouped the existing data, then found out the sample had more than the two mentioned types and then tried to bring in them into the grouping approach. I have added what I think your comment suggests as an alternative. – Martin Honnen Jan 04 '20 at 22:08