我正在从mysql移动到mongodb。昨天开始学习mongodb。Mongodb:索引聚合排序限制查询?
我有一个大的mysql表(超过400万行,每个超过300个字段),我正在移动到mongodb。
假设,产品表有以下字段 -
_id,类等300多个领域。
要找到前5类的产品与他们的计数一起,我有以下MySQL查询
Select category, count(_id) as N from products group by category order by N DESC limit 5;
我对category
场有一个指标,这个查询大约需要4.4秒在MySQL的。
现在,我已成功地将此表移动到mongodb,并且这是我的相应查询,用于查找其计数的前5个类别。
db.products.aggregate([{$group : {_id:"$category", N:{$sum:1}}},{$sort:{N: -1}},{$limit:5}]);
我再次有指数category
但查询似乎并不使用它(解释:真这么说的),它也正在围绕13.5秒此查询。
在阅读了关于mongodb聚合管道优化的更多信息之后,我发现我们需要在聚合之前使用排序来使索引工作,但我正在对聚合中的派生字段进行排序,因此无法在聚合函数之前进行。
如何在mongodb中优化像这样的查询?
============================================== ===========================的 输出解释
db.products.aggregate([{$group : {_id:"$category",N:{$sum:1}}},{$sort:{N: -1}},{$limit:5}], { explain: true });
{
"waitedMS" : NumberLong(0),
"stages" : [
{
"$cursor" : {
"query" : {
},
"fields" : {
"category" : 1,
"_id" : 0
},
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "mydb.products",
"indexFilterSet" : false,
"parsedQuery" : {
"$and" : [ ]
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"$and" : [ ]
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
}
}
},
{
"$group" : {
"_id" : "$category",
"N" : {
"$sum" : {
"$const" : 1
}
}
}
},
{
"$sort" : {
"sortKey" : {
"N" : -1
},
"limit" : NumberLong(5)
}
}
],
"ok" : 1
}
你能后的'explain'查询的输出,请 – Jaco
增加的产量解释查询。 – Aakash