【问题标题】:Is findById faster than findOne({userId: userId})?findById 比 findOne({userId: userId}) 快吗?
【发布时间】:2019-02-09 22:31:52
【问题描述】:

我的架构设置如下:

employment = new Schema({
  userId: {
    type: Schema.Types.ObjectId,
    ref: "Users"
  }
  ...
})

现在我正在通过在就业集合中搜索用户 ID 来查询用户的就业。将employmentId 引用保存在用户模型和findById 中会更快吗?还是差别不大?

感谢任何帮助谢谢

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    从性能的角度来看,我们拥有的 Reding 文档是相同的: findById 的定义: /** * Finds a single document by its _id field. `findById(id)` is almost* * equivalent to `findOne({ _id: id })`. If you want to query by a document's * `_id`, use `findById()` instead of `findOne()`. * * The `id` is cast based on the Schema before sending the command. * * This function triggers the following middleware. * * - `findOne()` * * \* Except for how it treats `undefined`. If you use `findOne()`, you'll see * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent * to `findOne({})` and return arbitrary documents. However, mongoose * translates `findById(undefined)` into `findOne({ _id: null })`. https://github.com/Automattic/mongoose/blob/master/lib/model.js

    【讨论】:

    • 嗨,感谢您的帮助,但我更想知道查询和 _id 与类型是 ObjectId 但不是 mongo 中对象的 id 的唯一字段之间的性能差异是什么
    • 啊,好的,那么,如果您计划收集太多,您应该考虑为该字段创建一个索引。创建索引会以与 _id 相同的方式提高性能。
    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2016-09-04
    • 2019-10-08
    相关资源
    最近更新 更多