$regexFind - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$regexFind

5.0 版的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的$regexFind运算符用于对文档中的字符串字段执行正则表达式匹配。它允许您搜索和提取与给定正则表达式模式匹配的特定子字符串。

参数

  • input:要搜索的字符串字段或表达式。

  • regex:要匹配的正则表达式模式。

  • options:(可选)为正则表达式指定可选参数的对象,例如区分大小写和多行匹配。支持的选项有i(不区分大小写)和m(多行)。

示例(MongoDB 外壳)

以下示例演示如何使用$regexFind运算符搜索name字段与特定正则表达式模式匹配的文档。

创建示例文档

db.users.insertMany([ { "_id": 1, name: "John Doe", email: "john@example.com" }, { "_id": 2, name: "Diego Ramirez", email: "diego@example.com" }, { "_id": 3, name: "Alejandro Rosalez", email: "alejandro@example.com" }, { "_id": 4, name: "Shirley Rodriguez", email: "shirley@example.com" } ]);

查询示例

db.users.aggregate([ { $project: { names: { $regexFind: { input: '$name', regex: 'j', options: 'i' } } } }, { $match: {names: {$ne: null}}} ])

此查询将返回该name字段包含字母 “j”(不区分大小写)的所有文档。

输出

[ { _id: 1, names: { match: 'J', idx: 0, captures: [] } } ]

注意:如果您的查询使用的是 Amazon DocumentDB 规划器版本 1,则必须使用提示才能使用索引。如果没有提示,查询可能会执行集合扫描。要查看您的计划程序版本并了解有关使用提示的更多信息,请参阅 [Amazon DocumentDB Query Planner 文档] (https://docs.aws.amazon.com/documentdb/latest/developerguide/query-planner.html)。

代码示例

要查看使用该$regexFind命令的代码示例,请选择要使用的语言的选项卡:

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 users = db.collection('users'); const results = await users.aggregate([ { $project: { names: { $regexFind: { input: "$name", regex: "john", options: "i" }}}}, { $match: {names: {$ne: null}}} ]).toArray(); console.log(results); await client.close(); } main();
Python
from pymongo import MongoClient client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] users = db['users'] results = list(users.aggregate([ { "$project": { "names": { "$regexFind": { "input": "$name", "regex": "john", "options": "i" }}}}, { "$match": {"names": {"$ne": None}}} ])) print(results) client.close()