本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$regex
$regex 運算子可讓您對字串欄位執行規則運算式比對。它是根據複雜模式搜尋和篩選文件的強大工具。
參數
範例 (MongoDB Shell)
以下範例示範 $regex運算子的使用情況,以搜尋 "name" 欄位符合特定模式的文件。
建立範例文件
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()