I want to find an account by name (in a MongoDB collection of 50K accounts)

我们用绳子找到In the usual way:

db.accounts.find({ name: 'Jon Skeet' })  // indexes help improve performance!

How about with regular expression? Is it an expensive operation?

db.accounts.find( { name: /Jon Skeet/ }) // worry! how indexes work with regex?

编辑:

According to WiredPrairie:

db.accounts.find( { name: /^Jon Skeet/ })  // indexes will help!'

MongoDB $regex

推荐答案

实际上根据文件,

如果该字段存在索引,则MongoDB与常规索引匹配

http://docs.mongodb.org/manual/reference/operator/query/regex/#index-use

换句话说:

对于/Jon Skeet/个正则表达式,mongo将完全扫描索引中的键,然后获取匹配的文档,这可能比集合扫描更快.

对于/^Jon Skeet/个正则表达式,mongo将只扫描索引中以正则表达式开头的范围,这将更快.

Mongodb相关问答推荐

MongoDB - 将属性添加到数组中的对象(如果不存在)

Mongo $sort然后$group,顺序能保证吗?

多键索引,性能问题

spring-data-mongodb 上的 TopN 聚合

用Golang减go mongodb中的两个字段

将MongoDB连接到前端?

MongoDB 2.1 聚合框架总和匹配名称的数组元素

无法连接到mongolab主机

在 Heroku 上使用 Node 读取、写入和存储 JSON

获取收集字节使用情况统计信息的pymongo方法?

mongodb 模式设计命名约定

如何知道 MongoDB 集合大小?

如何在 mongo JavaScript shell 中中止查询

mongo - 如何查询嵌套的 json

如何从 node.js 以编程方式执行 mongodump 命令?

如何在 Meteor 应用程序之间共享 MongoDB 集合?

使用 mongodb 在数组中查找子文档

mongoosefind()不返回结果

我需要手动关闭mongoose连接吗?

即使重新安装后,Mongo 仍在等待 27017