要为大文本字段建立索引,请ensureIndex()
与$regex一起使用以进行文本搜索。让我们创建一个包含文档的集合-
> db.demo46.ensureIndex({"Name":1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo46.insertOne({"Name":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e267004cfb11e5c34d898ed") } > db.demo46.insertOne({"Name":"John Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5e267009cfb11e5c34d898ee") } > db.demo46.insertOne({"Name":"Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e267011cfb11e5c34d898ef") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo46.find();
这将产生以下输出-
{ "_id" : ObjectId("5e267004cfb11e5c34d898ed"), "Name" : "John Smith" } { "_id" : ObjectId("5e267009cfb11e5c34d898ee"), "Name" : "John Doe" } { "_id" : ObjectId("5e267011cfb11e5c34d898ef"), "Name" : "Chris Brown" }
以下是索引大文本字段以使查询更快的查询-
> db.demo46.find({ Name: { $regex:/^John/}});
这将产生以下输出-
{ "_id" : ObjectId("5e267009cfb11e5c34d898ee"), "Name" : "John Doe" } { "_id" : ObjectId("5e267004cfb11e5c34d898ed"), "Name" : "John Smith" }