[英]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.