findOne 多次与具有多个 id 的 find()

findOne multiple times vs. find() with multiple ids

我很好奇调用 findOne() 十次和使用十个参数调用 find() 一次之间的性能差异。后者足够好吗?

一般来说,在你的环境中用你的数据进行测试是有意义的,但理论上的答案是:这取决于,但一般来说,是的 - 它提高了性能,因为它 减少了往返数据库的次数 ,并且 网络延迟通常是主要因素 除非您的查询效率非常低。这在生产环境和多个数据中心中更为突出,在本地主机上的问题较少。

问题是你的 10 个论点来自哪里 - 如果你想 select 一组 10 个元素的 id,一个 $in-query is more elegant and blazing fast. However, you could also use ten different queries in an $or-query and still reduce the number of round-trips. However, there are some pitfalls with $or and indexes that are described well in the documentation.

减少往返次数的主题也称为 N+1 problem in the context of pseudo-joins,人们普遍认为减少往返次数是关键。