我正在尝试在MongoDB中复制此SQL查询:
SELECT * FROM users WHERE
name LIKE CONCAT('%', :search_txt, '%') OR
surname LIKE CONCAT('%', :search_txt, '%') OR
CONCAT(name, ' ', surname) LIKE CONCAT('%', :search_txt, '%')
到目前为止,我设法使用此代码按名称或姓氏搜索,但我无法弄清楚如何通过名称+姓氏搜索
User.find(
{
"$or": [
{"name" : new RegExp(req.body.term, 'i')},
{"surname" : new RegExp(req.body.term, 'i')}
]
}
由于
答案 0 :(得分:0)
你走了:
User.aggregate({
$addFields: {
"fullname": {
$concat: [ "$name", ' ', "$surname" ]
}
}
}, {
$match: {
"$or": [
{"name": new RegExp(req.body.term, 'i')},
{"surname": new RegExp(req.body.term, 'i')},
{"fullname": new RegExp(req.body.term, 'i')}
]
}