MongoDB - 按名称或姓氏或姓名+姓氏查找用户

时间:2017-08-16 15:52:30

标签: mongodb find concat

我正在尝试在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')}
        ]
  }

由于

1 个答案:

答案 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')}
        ]        
    }