如何使用 MongoDB 中的 $regex?


以下是 MongoDB 中使用 $regex 的語法 −

db.yourCollectionName.find({yourFieldName: { $regex: yourValue}});

我們首先使用文件建立一個集合 −

> db.regularExpressionDemo.insertOne({"UserName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdffc25bf3115999ed51210")
}
> db.regularExpressionDemo.insertOne({"UserName":"JOHN"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdffc2ebf3115999ed51211")
}
> db.regularExpressionDemo.insertOne({"UserName":"john"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdffc35bf3115999ed51212")
}
> db.regularExpressionDemo.insertOne({"UserName":"JoHn"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdffc3ebf3115999ed51213")
}

以下是使用 find() 方法從集合顯示所有文件的查詢 −

> db.regularExpressionDemo.find();

這會產生以下輸出 −

{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }

以下是使用 $regex 的查詢 −

> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN'}});

這會產生以下輸出 −

{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }

現在,讓我們匹配所有情況。以下是查詢 −

> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN', $options: 'i' }});

這會產生以下輸出 −

{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }

更新於: 30-Jul-2019

264 瀏覽次數

開啟你的職業生涯

透過完成此課程獲得認證

開始
廣告