$regex - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$regex

$regex 演算子を使用すると、文字列フィールドで正規表現マッチングを実行できます。これは、複雑なパターンに基づいてドキュメントを検索およびフィルタリングするための強力なツールです。

パラメータ

  • regular expression: フィールドに一致する正規表現パターン。

  • $options: (オプション) 大文字と小文字の区別、グローバルマッチングなど、検索動作を変更するオプションを提供します。

例 (MongoDB シェル)

次の例は、「name」フィールドが特定のパターンに一致するドキュメントを検索するための $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" } ]

このクエリは、「name」フィールドが「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()