使用正则表达式时避免 MongoDB 性能问题
为了避免 MongoDB 中的性能问题,请使用索引的概念。让我们创建一个带文档的集合 -
> db.demo531.createIndex({"CountryName":"text","Name":"text"});{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo531.insertOne({CountryName:"US","Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2b60ef4dcbee04fbbbf2") } > db.demo531.insertOne({CountryName:"UK","Name":"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2b6cef4dcbee04fbbbf3") } > db.demo531.insertOne({CountryName:"AUS","Name":"chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2b74ef4dcbee04fbbbf4") } > db.demo531.insertOne({CountryName:"US","Name":"CHRIS"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2badef4dcbee04fbbbf5") }
在 find() 方法的帮助下,从集合中显示所有文档 -
> db.demo531.find();
这会产生以下输出 -
{ "_id" : ObjectId("5e8b2b60ef4dcbee04fbbbf2"), "CountryName" : "US", "Name" : "Chris" } { "_id" : ObjectId("5e8b2b6cef4dcbee04fbbbf3"), "CountryName" : "UK", "Name" : "David" } { "_id" : ObjectId("5e8b2b74ef4dcbee04fbbbf4"), "CountryName" : "AUS", "Name" : "chris" } { "_id" : ObjectId("5e8b2badef4dcbee04fbbbf5"), "CountryName" : "US", "Name" : "CHRIS" }
以下是使用正则表达式的查询 -
> db.demo531.find({CountryName: "US", "Name": { "$regex": "chris", "$options": "i" }}).limit(4);
这会产生以下输出 -
{ "_id" : ObjectId("5e8b2b60ef4dcbee04fbbbf2"), "CountryName" : "US", "Name" : "Chris" } { "_id" : ObjectId("5e8b2badef4dcbee04fbbbf5"), "CountryName" : "US", "Name" : "CHRIS" }
广告