XQuery 如何计算 JSON 中的所有 "spells"

XQuery how to count all the "spells" in JSON

我有以下 JSON 文件:

"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"
 }

}

你能帮助我如何使用 XQuery 计算 "type" = "Spell" 的所有拼写以及 "Type"= "charm" 的所有拼写。 JSON 文件要大得多,我只是不想将整个文件粘贴到这里。谢谢。

这似乎是一个直接的分组和计数:

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

或者,正如 Michael Kay 指出的那样,使用给定的值序列就足够了

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

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