为此,请在MongoDB中使用$regex。无论大小写,我们都将搜索名称为“ David”的文档字段值。让我们创建一个包含文档的集合-
> db.demo700.insertOne( { details: [ { Name:"david" }]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6e6b1551299a9f98c93ac") } > db.demo700.insertOne( { details: [ { Name:"Chris" }]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6e6b9551299a9f98c93ad") } > db.demo700.insertOne( { details: [ { Name:"DAVID" }]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6e6bf551299a9f98c93ae") } > db.demo700.insertOne( { details: [ { Name:"David" }]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6e6c4551299a9f98c93af") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo700.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea6e6b1551299a9f98c93ac"), "details" : [ { "Name" : "david" } ] } { "_id" : ObjectId("5ea6e6b9551299a9f98c93ad"), "details" : [ { "Name" : "Chris" } ] } { "_id" : ObjectId("5ea6e6bf551299a9f98c93ae"), "details" : [ { "Name" : "DAVID" } ] } { "_id" : ObjectId("5ea6e6c4551299a9f98c93af"), "details" : [ { "Name" : "David" } ] }
以下是查询以显示具有特定名称的文档,而不考虑大小写-
> db.demo700.find({"details.Name":{$regex:/^David$/i}});
这将产生以下输出-
{ "_id" : ObjectId("5ea6e6b1551299a9f98c93ac"), "details" : [ { "Name" : "david" } ] } { "_id" : ObjectId("5ea6e6bf551299a9f98c93ae"), "details" : [ { "Name" : "DAVID" } ] } { "_id" : ObjectId("5ea6e6c4551299a9f98c93af"), "details" : [ { "Name" : "David" } ] }