使用nodejs在mongo中跨多个string字段进行高效的文本search

有这样的10000个logging存储在mongo中。 如何在node.js中高效search以下内容 search条件可以基于mongo中的以下3个字段中的任何一个。 search标准将来自前端,他们可以search用户ID或员工名称或部门。 对于search只有一个input即将被采取,即只有一个领域,可以匹配任何这些领域,如谷歌search。

{ "userID": "01000900", "employeeName": "A Abc", "department": "Replenishment Boston" }, { "userID": "01001024", "employeeName": "K Gbc", "department": "Sales S-II - MA Core Urb" }, { "userID": "01001023", "employeeName": "Ga Va", "department": "Sales Phoenix" }, { "userID": "01000282", "employeeName": "D Din", "department": "Sales S-II - California - Me" } 

假设searchText是您从客户端获得的值。 使用正则expression式。

 { $or:[ {userId:{$regex: searchText, $options: 'i'}}, {employeeName:{$regex: searchText, $options: 'i'}}, {department:{$regex: searchText, $options: 'i'}} ] } 

您可以在以下所有3个字段上使用文本索引 :

 db.collection.createIndex( { userID: "text", employeeName: "text", department: "text" } ) 

查询db.collection.find( { $text: { $search: "string from input" } } )

应该做一些像谷歌search 。 文本查询语法的文档 。

您可以为每个字段创build索引。 通过这种方式,当你鳍一些数据将不会扫描整个文件。 search将基于索引。 所以你会立即得到结果。 现在创build索引。 假设你想在employeeName上创build一个索引,然后执行以下操作:

 db.collectionName.createIndex({employeeName:1});