本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$regexMatch
5.0 版的新增内容。弹性集群不支持。
Amazon DocumentDB 中的$regexMatch运算符用于对字符串字段执行正则表达式匹配。它返回一个布尔值(true或false),表示输入字符串是否与指定的模式匹配。
参数
-
input: 要根据正则表达式进行测试的字符串。 -
regex:要匹配的正则表达式模式。 -
options:(可选)用于修改正则表达式行为的标志,例如不区分大小写的匹配 (i) 或多行匹配 ()。m
示例(MongoDB 外壳)
以下示例演示如何使用$regexMatch运算符来检查名称是否以字母 “M” 开头。运算符false为每个文档返回true或。
创建示例文档
db.users.insertMany([ { "_id":1, name: "María García", email: "maría@example.com" }, { "_id":2, name: "Arnav Desai", email: "arnav@example.com" }, { "_id":3, name: "Martha Rivera", email: "martha@example.com" }, { "_id":4, name: "Richard Roe", email: "richard@example.com" }, ]);
查询示例
db.users.aggregate([ { $project: { name: 1, startsWithM: { $regexMatch: { input: "$name", regex: "^M", options: "i" } } } } ]);
输出
{ _id: 1, name: 'María García', startsWithM: true },
{ _id: 2, name: 'Arnav Desai', startsWithM: false },
{ _id: 3, name: 'Martha Rivera', startsWithM: true },
{ _id: 4, name: 'Richard Roe', startsWithM: false }
代码示例
要查看使用该$regexMatch命令的代码示例,请选择要使用的语言的选项卡: