如何使用 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" }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP