我有一个查找查询,需要检查文档中的数组是否存在任何元素。我想索引数组的大小来优化查询,但我不确定如何创建这样的索引。
我已经通过MongoDB C#驱动程序创建了过滤器:
Builders<Post>.Filter.And(new List<FilterDefinition<Post>>()
{
Builders<Post>.Filter.Eq(x => x.Category, Category.COLLECTION),
Builders<Post>.Filter.SizeGt(x => x.Details.References, 0)
})
文档类型长这样:
。
{
"_id" : ObjectId("577a271f2b365917c4d72678"),
"UserId" : ObjectId("577a26a32b365917c4d67e42"),
"Category" : NumberInt(4),
"Details" : {
"_id" : ObjectId("577a271f2b365917c4d72677"),
"References" : [
{
"RefId" : ObjectId("577a887b4fd1ae0e1c7b2035"),
"Order" : NumberInt(0),
"RefType" : NumberInt(1)
}
]
},
"Modified" : ISODate("2016-07-05T01:26:33.549+0000"),
"IsActive" : true
}
查询看起来是这样的:
{
"query" : {
"find" : "post",
"filter" : {
"UserId" : {
"$in" : [
ObjectId("577a26a12b365917c4d67dd5"),
ObjectId("577a26a12b365917c4d67dd3")
]
},
"IsActive" : true,
"$or" : [
{
"Category" : NumberInt(4),
"UserId" : {
"$nin" : [
]
},
"Details.References.0" : {
"$exists" : true
}
},
{
"Category" : {
"$ne" : NumberInt(4)
}
}
],
"Modified" : {
"$lt" : ISODate("2016-07-04T13:59:32.094+0000")
}
},
"sort" : {
"Modified" : NumberInt(-1)
},
"limit" : NumberInt(10)
},
"time" : NumberInt(33),
"docsScanned" : NumberInt(1125)
}
如您所见,它扫描了相当多的文档(1125)才找到正确的文档。我想进一步减少这个数字,但是我不确定该如何索引这部分内容:
"Details.References.0" : {
"$exists" : true
}
我该如何为引用长度创建索引?