鉴于记录游戏的以下文档结构:


{
...
"rightkingpercenthp":[1,1,1,1,1,1,1,1,1,1,1,0.94,0.95,0],
"gameDetails":[
	{"playername":"Calvino",
	...
	"unitsPerWave":[
		["grarl_unit_id:0.5|9.5"],
		["hydra_unit_id:3.5|6.5","veteran_unit_id:1.5|6","grarl_unit_id:3.5|5.5","peewee_unit_id:8.5|7"],	       ["hydra_unit_id:3.5|6.5","veteran_unit_id:1.5|6","veteran_unit_id:8.5|7","peewee_unit_id:8.5|6",
    "fatalizer_unit_id:2.5|5"],
    ...
    ]
}




我如何计算至少有一个游戏的数量gameDetails.unitsPerWave中的“ veteran_unit_id”(忽略名称后的坐标)?

最佳答案

您可以使用嵌套的$elemMatch运算符在嵌套的gamesDetails.unitsPerWave数组和与字符串开头匹配的正则表达式中进行查询:

db.col.count({
    'gameDetails.unitsPerWave': {$elemMatch: {$elemMatch: {$regex: /^veteran_unit_id/}}}
})

10-06 04:41