在 Mongo 中不區分大小寫的搜尋?
藉助 '$regex',可以在 MongoDB 中限制不區分大小寫的搜尋。語法如下 −
db.yourCollectionName.find({"yourFieldName" : { '$regex':'^yourValue$'}});
可以使用另一個正則表示式。語法如下 −
db.yourCollectionName.find({"Name" : { '$regex':/^yourValue$/i}});
為了理解這個概念,讓我們建立一個包含文件的 collection。建立包含文件的 collection 的查詢如下 −
> db.caseInsesitiveDemo.insertOne({"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bd66293c80e3f23815e83") } > db.caseInsesitiveDemo.insertOne({"Name":"Johnson"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bd66693c80e3f23815e84") } > db.caseInsesitiveDemo.insertOne({"Name":"Johny"}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bd66a93c80e3f23815e85") }
使用 find() 方法從 collection 中顯示所有文件。查詢如下 −
> db.caseInsesitiveDemo.find().pretty();
以下是輸出 −
{ "_id" : ObjectId("5c8bd66293c80e3f23815e83"), "Name" : "John" } { "_id" : ObjectId("5c8bd66693c80e3f23815e84"), "Name" : "Johnson" } { "_id" : ObjectId("5c8bd66a93c80e3f23815e85"), "Name" : "Johny" }
如果你使用下面這型別的正則表示式,那麼將能看到這些列出的文件。查詢如下 −
> db.caseInsesitiveDemo.find({"Name" : { '$regex' : 'John' }});
以下是輸出 −
{ "_id" : ObjectId("5c8bd66293c80e3f23815e83"), "Name" : "John" } { "_id" : ObjectId("5c8bd66693c80e3f23815e84"), "Name" : "Johnson" } { "_id" : ObjectId("5c8bd66a93c80e3f23815e85"), "Name" : "Johny" }
案例 1 − 如果你想限制所有那些文件的顯示,使用第一個查詢 −
> db.caseInsesitiveDemo.find({"Name" : { '$regex':'^John$'}});
以下是輸出 −
{ "_id" : ObjectId("5c8bd66293c80e3f23815e83"), "Name" : "John" }
檢視上面的示例輸出,只顯示了 'John'。
案例 2 − 如果你想限制所有那些文件的顯示,使用第二個查詢。
查詢如下 −
> db.caseInsesitiveDemo.find({"Name" : { '$regex':/^John$/i}});
以下是輸出 −
{ "_id" : ObjectId("5c8bd66293c80e3f23815e83"), "Name" : "John" }
廣告