MongoDBsearch匹配string部分的多个字段
这对我的同事MongoDB和NodeJs Devs来说是一个挑战
我有一个search表单,用户可以在其中input以下内容:
225/65R16 71T K715 Hankook
至于我的mongodb,我有一个收集与以下文档:
1- { _id: SomeId, Description: 225/65R16 71T K715, Brand: Hankook, Ref: 123455 } 2- { _id: SomeId, Description: 225/65R16 71T K715, Brand: Continental, Ref: 123456 } 3- { _id: SomeId, Description: 225/65R16 94T Energy, Brand: Hankook, Ref: 123457 }
我怎么能这样做,以便在search下面的任何组合时,我得到了上面的文档1和3的结果?
组合列表:
Hankook 225/65R16 225/65R16 Hankook 225 Hankook 225 Han
您可以尝试创build一个索引:
db.yourollection.createIndex({"Description":1,"Brand":1})
然后通过search值,例如:
mongoosemodel.find({$text:{$search: 225/65R16 Hankook}},{Description:1,Brand:1})
而且,如果您获得比预期更多的结果,则可以使用Javascript进行过滤。
您可以使用正则expression式匹配字段的开头,然后使用OR运算符 。
假设以下文件。
{ "Description" : "225/65R16 71T K715", "Brand" : "Hankook", "Ref" : 123455 } { "Description" : "225/65R16 71T K715", "Brand" : "Continental", "Ref" : 123455 } { "Description" : "225/65R16 94T", "Brand" : "Hankook", "Ref" : 123455 }
以下查询返回预期的结果。
> db.test.find({$or: [{Description: {$regex: '^225/65R16'}, Brand: {$regex: '^Hankook'}}]}) { "Description" : "225/65R16 71T K715", "Brand" : "Hankook", "Ref" : 123455 } {"Description" : "225/65R16 94T", "Brand" : "Hankook", "Ref" : 123455 } > db.test.find({$or: [{Description: {$regex: '^225'}, Brand: {$regex: '^Han'}}]}) { "Description" : "225/65R16 71T K715", "Brand" : "Hankook", "Ref" : 123455 } { "Description" : "225/65R16 94T", "Brand" : "Hankook", "Ref" : 123455 }
对于225/65R16
尽pipe没有办法避免匹配文档编号2,因为查询中不包含足够的消歧信息。
使用聚合来连接search字段,然后简单地使用正则expression式:
// Build a regex from your string, // Example : containing exactly all word, no order enter code here var a = "225/65R16 71T K715 Hankook" var ar = a.split(new RegExp("\\s")); // [ '225/65R16', '71T', 'K715', 'Hankook' ] var estr = "" ar.forEach(function(e){ estr += "(?=.*\b"+e+"\b)";}); var re = new RegExp("^.*"+estr+".*$"); // /^.*(?=.*\b225\/65R16\b)(?=.*\b71T\b)(?=.*\bK715\b)(?=.*\bHankook\b).*$/ enter code here db.a.aggregate([ { $project:{ st: {$concat:["$Brand"," ", "$Description"]}, _id:1, Description:1, Brand:1, Ref:1 } }, { $match:{ st: /^(?=.*\b225\/65R16\b)(?=.*\b71T\b)(?=.*\bK715\b)(?=.*\bHankook\b).*$/ } } ]) // output { "_id" : ObjectId("582f009da52585177f054ddc"), "Description" : "225/65R16 71T K715", "Brand" : "Hankook", "Ref" : "123455", "st" : "Hankook 225/65R16 71T K715" }