MongoDB $regex 运算符 i 或 I 用于不区分大小写的搜索
为此,你需要使用不区分大小写(i)。让我们创建一个带有文档的集合 -
> db.demo759.insertOne({SubjectName:"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5eb02ba95637cd592b2a4ae7") } > db.demo759.insertOne({SubjectName:"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5eb02baa5637cd592b2a4ae8") } > db.demo759.insertOne({SubjectName:"mongodb"}); { "acknowledged" : true, "insertedId" : ObjectId("5eb02baf5637cd592b2a4ae9") } > db.demo759.insertOne({SubjectName:"MONGODB"}); { "acknowledged" : true, "insertedId" : ObjectId("5eb02bb85637cd592b2a4aea") }
借助 find() 方法显示集合中的所有文档 -
> db.demo759.find();
这将产生以下输出 -
{ "_id" : ObjectId("5eb02ba95637cd592b2a4ae7"), "SubjectName" : "MySQL" } { "_id" : ObjectId("5eb02baa5637cd592b2a4ae8"), "SubjectName" : "MongoDB" } { "_id" : ObjectId("5eb02baf5637cd592b2a4ae9"), "SubjectName" : "mongodb" } { "_id" : ObjectId("5eb02bb85637cd592b2a4aea"), "SubjectName" : "MONGODB" }
以下是实现 MongoDB regex 运算符的查询 -
> db.demo759.find({"SubjectName":{$regex:/mongodb/i}});
这将产生以下输出 -
{ "_id" : ObjectId("5eb02baa5637cd592b2a4ae8"), "SubjectName" : "MongoDB" } { "_id" : ObjectId("5eb02baf5637cd592b2a4ae9"), "SubjectName" : "mongodb" } { "_id" : ObjectId("5eb02bb85637cd592b2a4aea"), "SubjectName" : "MONGODB" }
广告