什么更快:MongoDB / Mongoose中的`find()。limit(1)`或`findOne()`? [英] What's faster: `find().limit(1)` or `findOne()` in MongoDB/Mongoose?

查看:323
本文介绍了什么更快:MongoDB / Mongoose中的`find()。limit(1)`或`findOne()`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过的消息称MongoDB的 findOne() find()慢得多.limit(1),但后来我也听到了。实际上当前的事实是什么?

I've read sources that say MongoDB's findOne() is much slower than find().limit(1), but then I've also heard otherwise. What's actually the current truth?

2013年3月的文章:使用find()+ limit()要快得多,因为如果文件存在,findOne()将始终读取+返回文档.jit()只返回一个光标(或不返回),只有在迭代光标时才读取数据。

Article from March 2013: "It is significantly faster to use find() + limit() because findOne() will always read + return the document if it exists. find() just returns a cursor (or not) and only reads the data if you iterate through the cursor."

2011年SE回答:如果检索到find()。limit(1)文件,速度差异的数量级似乎消失了。而且,我无法重现与MongoDB JavaScript驱动程序的主要速度差异。我最初使用MongoDB Java驱动程序进行基准测试。

SE answer from 2011: "If the find().limit(1) document is retrieved, the orders of magnitude speed difference seems to disappear. Also, I could not reproduce the major speed difference with the MongoDB JavaScript driver. I originally benchmarked using the MongoDB Java driver."

我希望无论答案是什么,它都与使用Mongoose的 find()。sort()。limit(1) findOne()

I hope whatever the answer is, it is also consistent with using Mongoose's find().sort().limit(1) and findOne().

推荐答案

两者都是等同的快速。

当您执行 find()。limit(1)时不发送任何查询到服务器。您只需准备查询客户端。只要您不检索任何文档,您仍然可以修改光标,从而查询(例如通过添加 sort )。

When you do find().limit(1) no query is send to the server. You just prepare the query client side. As long as you don't retrieve any documents you can still modify the cursor, thus the query (eg by adding a sort).

因此,如果您只对 find()。limit(1)进行基准测试,您会发现它的速度要快得多,因为查询未执行。可以说你正在对无用的代码进行基准测试。

So if you benchmark only the find().limit(1) you'll find it's a lot faster, because the query isn't executed. Arguably you're benchmarking useless code.

这篇关于什么更快:MongoDB / Mongoose中的`find()。limit(1)`或`findOne()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆