要在MongoDB中进行全文搜索,请使用$text。$text对字段的内容执行文本搜索。让我们创建一个包含文档的集合-
> db.demo654.createIndex({Name:"text"}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo654.insertOne({"Name":"John Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04e924deddd72997713c8") } > db.demo654.insertOne({"Name":"Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04e9d4deddd72997713c9") } > db.demo654.insertOne({"Name":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04ea54deddd72997713ca") } > db.demo654.insertOne({"Name":"David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04eb24deddd72997713cb") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo654.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea04e924deddd72997713c8"), "Name" : "John Doe" } { "_id" : ObjectId("5ea04e9d4deddd72997713c9"), "Name" : "Chris Brown" } { "_id" : ObjectId("5ea04ea54deddd72997713ca"), "Name" : "John Smith" } { "_id" : ObjectId("5ea04eb24deddd72997713cb"), "Name" : "David Miller" }
以下是在MongoDB中执行全文本搜索的查询-
> db.demo654.find({ $text: { $search: "John" } } );
这将产生以下输出-
{ "_id" : ObjectId("5ea04ea54deddd72997713ca"), "Name" : "John Smith" } { "_id" : ObjectId("5ea04e924deddd72997713c8"), "Name" : "John Doe" }