如何在MongoDB中按名字和姓氏搜索用户? [英] How to search for users by both first and last name with MongoDB?
问题描述
我有一个基本的用户集合,这些用户具有他们的 firstName
, lastName
和其他一些详细信息.
I have a basic collection of users that have their firstName
, lastName
and a few other details.
我如何简单地通过两个名称的组合来搜索用户,或者进行部分搜索?
How would I simply search for users by a combination of both names, or partial search?
例如,对于以下项的集合:
For example, for a collection of:
{
firstName: Bob,
lastName: Jerry
}, {
firstName: Clark,
lastName: Mcbobby
}
如果搜索词为 bob
,则将返回两个用户,因为第一个文档 firstName
是bob,而最后一个用户 lastName
包含 bob
.如果 bob j
是搜索词,则将仅返回第一个文档,因为如果两个名称组合在一起,则它等于与搜索词匹配的 Bob Jerry
.
If the search term was bob
, both users would be returned since the first documents firstName
is bob, and the last users lastName
contains bob
. If bob j
was the search term, just the first document would be returned since if both names are combine, it equals Bob Jerry
which matches the search term.
我尝试创建一个基本的 aggregate
来连接名称,然后进行匹配,尽管Mongoose不断向我抛出错误:参数必须是聚合管道运算符
.
I tried creating a basic aggregate
to concatenate the names and then make a match, although Mongoose kept throwing me an error of: Arguments must be aggregate pipeline operators
.
这是我当前的代码:
User.aggregate({
$project: { "name" : { $concat : [ "$firstName", " ", "$lastName" ] } },
$match: {"name": {$regex: "/bob j/i"}}
}).exec(function(err, results) {
...
});
推荐答案
我在您的代码中发现了几个错误,这些错误导致了不希望的结果.
I see couple of mistakes in your code causing undesired result.
-
聚合管道接受一组聚合框架操作.就您而言,您缺少
[]
运算符.应该是
User.aggregate([{{$ project ...},{$ match ...}])
在$ match阶段,您使用的是正则表达式,如果您使用的是/../
风格的正则表达式,则无需将其用字符串引号引起来.它应该是/bob j/i
In $match stage you are using regex, if you are using /../
style of regex, you don't need to wrap it around string quotes. It should be /bob j/i
这是完成的示例:
User.aggregate([
{$project: { "name" : { $concat : [ "$firstName", " ", "$lastName" ] } }},
{$match: {"name": {$regex: /bob j/i}}}
]).exec(function(err, result){
console.log(result);
});
您应该在屏幕上看到 [{_id:574c3e20be214bd4078a9149,名称:'Bob Jerry'}]
.
这篇关于如何在MongoDB中按名字和姓氏搜索用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!