Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$regex
该$regex运算符允许您对字符串字段执行正则表达式匹配。它是基于复杂模式搜索和筛选文档的强大工具。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$regex运算符来搜索 “名称” 字段与特定模式匹配的文档。
创建示例文档
db.users.insertMany([
{ name: "John Doe" },
{ name: "Jane Smith" },
{ name: "Alice Johnson" },
{ name: "Bob Williams" },
{ name: "Charlie Davis" }
]);
查询示例
db.users.find({ name: { $regex: /^A/ } })
输出
[
{ "_id" : ObjectId("..."), "name" : "Alice Johnson" }
]
此查询将返回 “名称” 字段以字母 “A” 开头的所有文档。
代码示例
要查看使用该$regex命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function main() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const collection = db.collection('users');
const results = await collection.find({ name: { $regex: /^A/ } }).toArray();
console.log(results);
await client.close();
}
main();
- Python
-
from pymongo import MongoClient
def main():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['users']
results = list(collection.find({ 'name': { '$regex': '^A' } }))
print(results)
client.close()
if __name__ == "__main__":
main()