我使用 Spring 中的 MongoTemplate 来访问 MongoDB。
final Query query = new Query(Criteria.where("_id").exists(true));
query.with(new Sort(Direction.ASC, "FIRSTNAME", "LASTNAME", "EMAIL"));
if (count > 0) {
query.limit(count);
}
query.skip(start);
query.fields().include("FIRSTNAME");
query.fields().include("LASTNAME");
query.fields().include("EMAIL");
return mongoTemplate.find(query, User.class, "users");
我在 MongoDB 中生成了 400.000 条记录。 当在不使用上面编写的排序行的情况下询问前 25 个用户时,我在不到 50 毫秒的时间内得到了结果。
排序后,它会持续超过 4 秒。
然后我为 FIRSTNAME、LASTNAME、EMAIL 创建了索引。单一索引,而非组合索引
mongoTemplate.indexOps("users").ensureIndex(new Index("FIRSTNAME", Order.ASCENDING));
mongoTemplate.indexOps("users").ensureIndex(new Index("LASTNAME", Order.ASCENDING));
mongoTemplate.indexOps("users").ensureIndex(new Index("EMAIL", Order.ASCENDING));
创建这些索引后,查询再次持续超过 4 秒。
我的错误是什么?
--编辑 MongoDB 将其写在控制台上...
Thu Jul 04 10:10:11.442 [conn50] query mydb.users query: { query: { _id: { $exists: true } }, orderby: { LASTNAME: 1, FIRSTNAME: 1, EMAIL: 1 } } ntoreturn:25 ntoskip:0 nscanned:382424 scanAndOrder:1 keyUpdates:0 numYields: 2 locks(micros) r:6903475 nreturned:25 reslen:3669 4097ms
最佳答案
您必须按此顺序为 FIRSTNAME
、LASTNAME
和 EMAIL
创建复合索引,并且所有索引均按升序排列。
关于java - MongoDB find 在带索引和不带索引的情况下速度相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17465114/