Javascript 添加索引后搜索速度变慢

Javascript 添加索引后搜索速度变慢,javascript,node.js,database,mongodb,indexing,Javascript,Node.js,Database,Mongodb,Indexing,mongodb集合存储以下格式的文档: {url: "/url", ip: "0.0.0.0", ua:"useragent", time: 51} 我使用以下代码进行选择 collection.aggregate([ { $group: { _id: "$url", count: { $sum: 1}, time: { $sum: "$time"} }}, { $project: { _id: 1, count:1, time: { $round : [{$divide: ["$time",

mongodb集合存储以下格式的文档:

{url: "/url", ip: "0.0.0.0", ua:"useragent", time: 51}
我使用以下代码进行选择

collection.aggregate([
{ $group: { _id: "$url", count: { $sum: 1}, time: { $sum: "$time"} }},
{ $project: { _id: 1, count:1, time: { $round : [{$divide: ["$time", "$count"]}, 0] } } },
{ $sort: { count : -1 } },
{ $limit: 100}
]).toArray(callback);
对于
700000
文档,请求需要3秒钟,这在某种程度上很长,在
url
字段中添加了一个索引

collection.createIndex({ url: 1})
之后,请求的处理时间开始延长2倍,删除索引后,执行时间恢复到3秒

  • 如何加速查询执行

  • 为什么添加索引会导致糟糕的结果


  • 您可以尝试在聚合中使用
    explain
    。我猜它正在使用基于索引的搜索,但仍然需要查找每个元素以获得
    time
    属性。您可以尝试使用
    url
    time
    collection.createIndex({url:1,time:1})
    添加组合索引。您可以尝试在聚合中使用
    explain
    。我猜它正在使用基于索引的搜索,但仍然需要查找每个元素以获得
    time
    属性。您可以尝试使用
    url
    time
    collection.createIndex({url:1,time:1})
    添加组合索引。