Mongodb 检查存在计数与 findOne 性能

Mongodb check existence count vs findOne performance

我想知道我的数据库中是否存在某个文档,我有点好奇,最好的方法是什么? 使用

User.findOne(query).select('_id')

User.count(query)

一方面,findOne return 是一个 24 位的十六进制字符串,而 count 将 return 只是一个整数;另一方面,.count 它将遍历整个集合,而 .findOne 将在第一个匹配的文档处停止。

我找到的唯一与此相关的答案是 this 问题,找不到其他任何答案,该答案支持 .count,Mongo 在这方面做了很多工作性能,6年前的问题了

什么更有价值?内存 (findOne) 还是处理能力 (count)?

在某些情况下 count 可能会给您不准确的结果。此外,性能会比 findOne() 慢。

On a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.

After an unclean shutdown of a mongod using the Wired Tiger storage engine, count statistics reported by count() may be inaccurate.

鉴于您确实希望检查文档是否存在,我认为 findOne() 是更好的选择。