19

嗨,我正在使用猫鼬来搜索我收藏中的人。

/*Person model*/
{
    name: {
       first: String,
       last: String
    }
}

现在我想搜索有查询的人:

let regex = new RegExp(QUERY,'i');

Person.find({
   $or: [
      {'name.first': regex},
      {'name.last': regex}
   ]
}).exec(function(err,persons){
  console.log(persons);
});

如果我搜索John我会得到结果(如果我搜索Jo的事件)。但是,如果我搜索John Doe ,我显然不会得到任何结果。

如果我将QUERY更改为John|Doe,我会得到结果,但它会返回所有姓氏/名字中包含JohnDoe的人。

接下来是尝试使用猫鼬文本搜索:

首先将字段添加到索引:

PersonSchema.index({
   name: {
      first: 'text',
      last: 'text'
   }
},{
   name: 'Personsearch index',
   weights: {
      name: {
          first : 10,
          last: 10
   }
}
});

然后修改 Person 查询:

Person.find({ 
    $text : { 
        $search : QUERY
    } 
},
{ score:{$meta:'textScore'} })
.sort({ score : { $meta : 'textScore' } })
.exec(function(err,persons){
    console.log(persons);
});

这工作得很好!现在它只返回与整个名字/姓氏匹配的人:

->约翰返回值

-> Jo没有返回值

有没有办法解决这个问题?

首选没有外部插件的答案,但也希望有其他答案。

4

3 回答 3

29

正则表达式可以帮助你。

Person.find({ "name": { "$regex": "Alex", "$options": "i" } },
function(err,docs) { 
});
于 2018-01-14T14:28:15.293 回答
9

您可以使用将aggregate名字和姓氏连接在一起的管道来执行此操作$concat,然后对其进行搜索:

let regex = new RegExp(QUERY,'i');

Person.aggregate([
    // Project the concatenated full name along with the original doc
    {$project: {fullname: {$concat: ['$name.first', ' ', '$name.last']}, doc: '$$ROOT'}},
    {$match: {fullname: regex}}
], function(err, persons) {
    // Extract the original doc from each item
    persons = persons.map(function(item) { return item.doc; });
    console.log(persons);
});

然而,性能是一个问题,因为它不能使用索引,因此需要完整的集合扫描。

您可以通过在该$project阶段之前使用可以使用索引来减少管道其余部分需要查看的文档集的$match查询来缓解这种情况。

因此,如果您单独索引name.firstname.last然后将搜索字符串的第一个单词作为锚定查询(例如/^John/i),您可以在管道的开头添加以下内容:

{$match: $or: [
  {'name.first': /^John/i},
  {'name.last': /^John/i}
]}

显然,您需要以编程方式生成“第一个单词”正则表达式,但希望它能给您带来想法。

于 2016-02-02T13:35:44.337 回答
-1

一个)。在集合中的单个字段中进行部分文本搜索:

如果我们想在集合中的单个字段中搜索,我们可以汇总使用该代码

{
  $match: {
    name: {
      $regex: “String seraching”,
      ‘$options’: ‘i’
      }
   }
}

乙)。通过集合中的多个字段进行部分文本搜索:

如果我们想在特定集合中搜索多个字段(多个字段),那么我们可以在聚合查询中使用该代码

{
  $match: {
    $or: [
     { name: {
       $regex: “String to be searched”,
       ‘$options’: ‘i’
     }},
     { email: {
       $regex: String to be searched,
       ‘$options’: ‘i’
     }}
    ]
}

},

于 2021-09-14T18:33:44.457 回答