| 写法一 | {name: /alice/i} |
|---|---|
| 写法二 | {name: {$regex: "^张", $options: "i"}} |
| 索引前提 | ^ 前缀锚定且不使用 i 选项 |
示例
示例
db.users.find({ name: { $regex: "^张", $options: "i" } })
db.users.find({ name: /alice/i })不含 ^ 的子串匹配一律全集合扫描;用户输入直接拼入正则存在 ReDoS 与语义偏差风险。
字符串正则匹配:预编译正则对象或 $regex/$options 表达式都可;只有锚定前缀(^)且区分大小写时才有机会走索引。
| 写法一 | {name: /alice/i} |
|---|---|
| 写法二 | {name: {$regex: "^张", $options: "i"}} |
| 索引前提 | ^ 前缀锚定且不使用 i 选项 |
db.users.find({ name: { $regex: "^张", $options: "i" } })
db.users.find({ name: /alice/i })