不区分大小写的 MongoDB 搜索查询?
对于不区分大小写的搜索,请在 find() 方法中使用 regex。以下是用法语法 −
db.demo572.find({"yourFieldName" : { '$regex':/^yourValue$/i}});
为了理解上述语法,让我们创建一个包含文档的集合 −
> db.demo572.insertOne({"CountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e915f0e581e9acd78b427f1") } > db.demo572.insertOne({"CountryName":"UK"});{ "acknowledged" : true, "insertedId" : ObjectId("5e915f17581e9acd78b427f2") } > db.demo572.insertOne({"CountryName":"Us"});{ "acknowledged" : true, "insertedId" : ObjectId("5e915f1b581e9acd78b427f3") } > db.demo572.insertOne({"CountryName":"AUS"});{ "acknowledged" : true, "insertedId" : ObjectId("5e915f20581e9acd78b427f4") } > db.demo572.insertOne({"CountryName":"us"});{ "acknowledged" : true, "insertedId" : ObjectId("5e915f25581e9acd78b427f5") }
使用 find() 方法显示集合中的所有文档 −
> db.demo572.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" } { "_id" : ObjectId("5e915f17581e9acd78b427f2"), "CountryName" : "UK" } { "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" } { "_id" : ObjectId("5e915f20581e9acd78b427f4"), "CountryName" : "AUS" } { "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }
以下是对不区分大小写搜索的查询 −
> db.demo572.find({"CountryName" : { '$regex':/^US$/i}});
这将产生以下输出 −
{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" } { "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" } { "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }
广告