如何在 MongoDB 中进行不区分大小写的查询?
对于不区分大小写的查询,请在 MongoDB 中使用正则表达式。让我们创建一个包含这些文档的集合 −
> db.demo314.insertOne({"Name":"Chris brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50d742f8647eb59e562056") } > db.demo314.insertOne({"Name":"David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50d743f8647eb59e562057") } > db.demo314.insertOne({"Name":"CHRIS BROWN"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50d744f8647eb59e562058") } > db.demo314.insertOne({"Name":"DAVID MILLER"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50d747f8647eb59e562059") } > db.demo314.insertOne({"Name":"chris brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50d749f8647eb59e56205a") }
在集合中显示所有文档,可以使用 find() 方法 −
> db.demo314.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e50d742f8647eb59e562056"), "Name" : "Chris brown" } { "_id" : ObjectId("5e50d743f8647eb59e562057"), "Name" : "David Miller" } { "_id" : ObjectId("5e50d744f8647eb59e562058"), "Name" : "CHRIS BROWN" } { "_id" : ObjectId("5e50d747f8647eb59e562059"), "Name" : "DAVID MILLER" } { "_id" : ObjectId("5e50d749f8647eb59e56205a"), "Name" : "chris brown" }
以下是不区分大小写的查询。该查询会显示文档中出现的每个可能情况中的“chris brown”名称 −
> db.demo314.find({"Name":/chris brown/i});
这将产生以下输出 −
{ "_id" : ObjectId("5e50d742f8647eb59e562056"), "Name" : "Chris brown" } { "_id" : ObjectId("5e50d744f8647eb59e562058"), "Name" : "CHRIS BROWN" } { "_id" : ObjectId("5e50d749f8647eb59e56205a"), "Name" : "chris brown" }
广告