对于文本搜索,您需要将$text与$search一起使用。让我们创建一个包含文档的集合-
> db.demo156.createIndex({"StudentName":"text"}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo156.insertOne({"StudentName":"Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3547e8fdf09dd6d08539e6") } > db.demo156.insertOne({"StudentName":"John Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3547f2fdf09dd6d08539e7") } > db.demo156.insertOne({"StudentName":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3547f7fdf09dd6d08539e8") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo156.find();
这将产生以下输出-
{ "_id" : ObjectId("5e3547e8fdf09dd6d08539e6"), "StudentName" : "Chris Brown" } { "_id" : ObjectId("5e3547f2fdf09dd6d08539e7"), "StudentName" : "John Doe" } { "_id" : ObjectId("5e3547f7fdf09dd6d08539e8"), "StudentName" : "John Smith" }
以下是在MongoDB中实现文本搜索的查询-
> db.demo156.find({ $text: { $search: "John" } } )
这将产生以下输出-
{ "_id" : ObjectId("5e3547f7fdf09dd6d08539e8"), "StudentName" : "John Smith" } { "_id" : ObjectId("5e3547f2fdf09dd6d08539e7"), "StudentName" : "John Doe" }