为了避免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" }