是否可以在查找查询中的$elemMatch投影之后进行筛选



我在一个名为"variations"的集合中有这样的文档:

{
"_id" : "An_FM000900_Var_10_100042505_100042505_G_A",
"analysisId" : "FM000900",
"chromosome" : 10,
"start" : 100042505,
"end" : 100042505,
"size" : 1,
"reference" : "G",
"alternative" : "A",
"effects" : [ 
{
"_id" : "Analysis:FM000900-Variant:An_FM000900_Var_10_100042505_100042505_G_A-Effect:0",
"biotype" : "protein_coding",
"impact" : "LOW",
},
{
"_id" : "Analysis:FM000900-Variant:An_FM000900_Var_10_100042505_100042505_G_A-Effect:1",
"biotype" : "protein_coding",
"impact" : "MODERATE",
}
]
}

我想在该集合中找到符合某些标准的文档("analysisId":"FM000900"),然后我想在"effects"数组字段上投影,以只显示"effect"数组中满足某些标准的第一个元素("biotype":"protein_coding"one_answers"impact":"MODERATE")。

问题是,我只想显示主"变体"文档,当且仅当"effects"数组中至少有一个元素满足条件时。

使用以下查询,我得到了预期的结果,只是得到了"effects"数组字段为空的"variant"文档。

db.getCollection('variants').find(  
{
"analysisId":"FM000900"
}
,
{ 
"effects":{
"$elemMatch" : {
"biotype" : "protein_coding",
"impact" : "MODERATE"
}
}
}     
).skip(0).limit(200)

如果可能的话,有人能转换这个查询,只得到投影后"effect"数组中有某个元素的"variant"文档吗?

如果可能的话,可以用另一种方式完成,而不使用聚合框架吗?因为这个收藏有数百万份文件,而且必须具有表演性。

非常感谢,伙计们!!!

除了投影之外,只需使用$elemMatch作为查询运算符,它将过滤至少有一个符合所有条件的效果数组元素的变体。因此,您的查询将是:

db.getCollection('variants').find(  
{
"analysisId":"FM000900",
"effects":{
"$elemMatch" : {
"biotype" : "protein_coding",
"impact" : "MODERATE"
}
}
}
,
{ 
"effects":{
"$elemMatch" : {
"biotype" : "protein_coding",
"impact" : "MODERATE"
}
}
}     
).skip(0).limit(200)

此外,包含查询和投影的复合多关键字索引可以提高读取性能,但要小心使用,因为它会大大降低写入性能。

最新更新