简体   繁体   English

使用mongodb从对象数组中的搜索中查找完全匹配

[英]Find an exact match from search in array of objects using mongodb

I'm querying for all of the data in my database and running a search against it using the following code.我正在查询数据库中的所有数据,并使用以下代码对其进行搜索。

The problem is that it doesn't query for an exact match, it's a keyword search.问题在于它不查询完全匹配,而是关键字搜索。
If I enter "dog colorado" it returns all results containing the words "dog" and "colorado".如果我输入“dog colorado”,它会返回包含“dog”和“colorado”这两个词的所有结果。

I'd like it to return results for "dog colorado".我希望它返回“狗科罗拉多”的结果。

I am using Mongodb for reference我正在使用 Mongodb 作为参考

$http.get('/sapi/search/contractors?query=' + $scope.data.query)
  .then(function(res) {
    console.log("response from query", res.data);
    // if it gets all the data
    if (res.data.users && res.data.users.length) {
      $scope.items = _.filter(res.data.users, function(user) {
        return user.roles && user.roles.indexOf('contractor') !== -1 && user.firstName;
      });
    } else {
      console.log('no items', res);
      $scope.items = null;
    }

Alright you are using mongodb, so you need to use the mongo querying system with a regex to get exact match.好吧,您正在使用 mongodb,因此您需要使用带有正则表达式的 mongo 查询系统来获得精确匹配。

db.collection.find({yourattributeyouwanttomatch: {$regex: new RegExp('^' +  query + '$', 'i')}})

You can remove the 'i' if you want case sensitive and you can remove the ^ and $ if you want to match anywhere in the string.如果您想区分大小写,您可以删除 'i',如果您想匹配字符串中的任何位置,您可以删除 ^ 和 $。

you can use this to search from array of object in mongo for eg:您可以使用它从 mongo 中的对象数组中搜索例如:

{
  _id: 1,
  persons: [
            { name: 'ABC',
              age: 10
            },
            { name: 'ABD',
              age: 12
            }
          ]
}

mongo query:蒙戈查询:

db.users.find({person: {$elemMatch: {name:'ABC', age:10}}})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以使用phpQuery找到完全匹配的内容吗? - Can I find exact match using phpQuery? 如何搜索完全匹配 - How to search for exact match 如何从对象数组中搜索“标题”并仅返回与searchTerm匹配的对象? - How do i search 'titles' from array of objects & return only objects that match searchTerm? 使用简单数组中的jquery自动完成功能从头开始自动完成完全匹配 - auto complete exact match from start using jquery autocomplete from simple array DataTables列搜索完全匹配 - DataTables column search for exact match jQuery DataTable-搜索完全匹配 - JQuery DataTable - Search for exact match 使用分层的.reduce()OR .filter()函数,根据单独的搜索数组查找对象内的对象aray? - Find objects inside an objects aray, based on a seperate search array, using a layered .reduce() OR .filter() function? 如何从给定的项目数组中找到其数据与至少一个项目的条件匹配的文档 - mongoDB - How to find documents that their data match a condition on at least one item from a given array of items - mongoDB 数据表在标题搜索列上搜索完全匹配 - Datatables Search exact match on header search column 搜索完全匹配并突出显示jquery数据表正则表达式 - search exact match and highlight jquery datatable regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM