我在我的项目中使用MongoDB Java驱动程序执行查询(查找、聚合、MapReduce等)来处理一个大集合(5百万个文档)。
驱动程序版本为:
<!-- MongoDB driver-->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.3</version>
</dependency>
我的问题是,当我使用Java中的API并带有一些筛选条件时,操作需要15秒钟。
....
Iterable<Document> messageList = collection.find().filter(... some filters).sort(... fields);
// Find documents
for (Document message : messageList) {
....
// some code
....
}
我检查了Mongo服务器日志文件,并发现跟踪是一个COMMAND而不是一个QUERY:
如果我从mongodb客户端(Robomongo)运行相同的查询,它只需要0.05毫秒。2015-09-01T12:11:47.496+0200 I COMMAND [conn503] command b.$cmd command: count { count: "logs", query: { timestamp: { $gte: new Date(1433109600000) }, aplicacion: "APP1", event: "Event1" } } planSummary: IXSCAN { timestamp: 1, aplicacion: 1 } keyUpdates:0 writeConflicts:0 numYields:19089 reslen:44 locks:{ Global: { acquireCount: { r: 19090 } }, MMAPV1Journal: { acquireCount: { r: 19090 } }, Database: { acquireCount: { r: 19090 } }, Collection: { acquireCount: { R: 19090 } } } 14297ms
db.getCollection('logs').find({ timestamp: { $gte: new Date(1427839200000) }, aplicacion: "APP1", event: "Event1" })
在服务器日志中,查询被记录为 QUERY
所有使用Java命令进行的查询(查找,聚合等)是否都被转换了?性能远不如Mongo shell。
collection.find(... some filters...).sort(... fields);
吗?这种方法不使用MongoCursor
的.filter
方法,而是在打开游标时提供筛选条件。这更接近于你的 shell 查询。 - Philippsort
。也许这就是罪魁祸首? - Philipp