MongoDB:如何在$or内索引范围查询或使用排序
我在MongoDB中的文档如下所示:MongoDB:如何在$or内索引范围查询或使用排序,mongodb,performance,indexing,Mongodb,Performance,Indexing,我在MongoDB中的文档如下所示: { "_id" : ObjectId("59839527ceaa98f14349233a"), "entityId" : "10", "a" : 1, "b" : 1, "c" : 1, "d" : 1 } 我的基本查询如下所示: db.getCollection('test').find( { "entityId" : {$in : ["10", "11"]}, $or : [
{
"_id" : ObjectId("59839527ceaa98f14349233a"),
"entityId" : "10",
"a" : 1,
"b" : 1,
"c" : 1,
"d" : 1
}
我的基本查询如下所示:
db.getCollection('test').find(
{
"entityId" : {$in : ["10", "11"]},
$or : [
{"a" : {$gt : 2}},
{"a" : 2, "_id" : {$gt : ObjectId("59839527ceaa98f14349233a")}}
]
}).sort({"a" : 1})
注意:在我的其他查询中,仅在$or和排序中更改。例如,下面是我查询的另一个示例(仅a
更改为b
):
目前,我正在创建复合索引,如下所示:
db.getCollection('test').createIndex({"entityId" : 1, "a" : 1, "_id" : 1})
db.getCollection('test').createIndex({"entityId" : 1, "b" : 1, "_id" : 1})
当我运行第一个explain()
查询时,第一个索引被挑选得很好,但是当我运行第二个查询时,我注意到第一个索引再次被挑选,第二个索引在rejectedPlan
上。我做错了什么?还有其他更好的索引吗
db.getCollection('test').createIndex({"entityId" : 1, "a" : 1, "_id" : 1})
db.getCollection('test').createIndex({"entityId" : 1, "b" : 1, "_id" : 1})