如何在 MongoDB 上执行不区分大小写的查询?


使用 regexp 在 MongoDB 上进行不区分大小写的查询。为了理解这个概念,我们使用文档创建一个集合。创建具有文档的集合的查询如下所示 −

> db.caseInsensitiveDemo.insertOne({"UserName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f6fec8d10a061296a3c45")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"DAVID"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f6ff28d10a061296a3c46")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"david"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f6ffa8d10a061296a3c47")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f70008d10a061296a3c48")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f70058d10a061296a3c49")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f70098d10a061296a3c4a")
}
> db.caseInsensitiveDemo.insertOne({"UserName":"daVID"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f70138d10a061296a3c4b")
}

使用 find() 方法显示集合中的所有文档。该查询如下所示 −

> db.caseInsensitiveDemo.find().pretty();

以下是输出 −

{ "_id" : ObjectId("5c6d7a67f2db199c1278e7ef"), "Name" : "John" }
{ "_id" : ObjectId("5c6d7ad6f2db199c1278e7f0"), "Name" : "JOHN" }
{ "_id" : ObjectId("5c7f6fec8d10a061296a3c45"), "UserName" : "David" }
{ "_id" : ObjectId("5c7f6ff28d10a061296a3c46"), "UserName" : "DAVID" }
{ "_id" : ObjectId("5c7f6ffa8d10a061296a3c47"), "UserName" : "david" }
{ "_id" : ObjectId("5c7f70008d10a061296a3c48"), "UserName" : "Carol" }
{ "_id" : ObjectId("5c7f70058d10a061296a3c49"), "UserName" : "Mike" }
{ "_id" : ObjectId("5c7f70098d10a061296a3c4a"), "UserName" : "Sam" }
{ "_id" : ObjectId("5c7f70138d10a061296a3c4b"), "UserName" : "daVID" }

以下是在 MongoDB 上执行不区分大小写的查询 −

> db.caseInsensitiveDemo.find({UserName: /^david$/i } ).pretty();

以下是输出 −

{ "_id" : ObjectId("5c7f6fec8d10a061296a3c45"), "UserName" : "David" }
{ "_id" : ObjectId("5c7f6ff28d10a061296a3c46"), "UserName" : "DAVID" }
{ "_id" : ObjectId("5c7f6ffa8d10a061296a3c47"), "UserName" : "david" }
{ "_id" : ObjectId("5c7f70138d10a061296a3c4b"), "UserName" : "daVID" }

更新日期: 30-Jul-2019

199 次浏览

开启你的职业生涯

完成课程即可获得认证

开始
广告