【问题标题】:First Name and Last Name Combine search in mongoDBmongoDB中的名字和姓氏组合搜索
【发布时间】:2020-01-19 01:51:29
【问题描述】:

我有两个字段 FirstName 和 LastName 存储在 MongoDB.from Frontend 中,我收到一个字符串,其中包含用空格分隔的名字和姓氏,我需要一个查找查询来搜索名字和姓氏的组合。

这里是例如。场景

在数据库中我有以下对象

{ firstName: "Hemant Kumar", lastName: "Rajpoot" };

如果我收到"Hemant Kumar Rajpoot",它应该匹配。如果可能,请不要给出聚合解决方案。

【问题讨论】:

标签: javascript node.js mongodb mongoose mongodb-query


【解决方案1】:

您可以将$expr$eq$concat 组合使用。

例子:

db.yourCollection.find({
  $expr: {
    $eq: [
      {$concat: ["$firstName", " ", "$lastName"]}, 
      "Hemant Kumar Rajpoot" // your full name to search here
    ]
  }
})

【讨论】:

    【解决方案2】:

    就像检查输入的字段(firstnamelastname)是否与数据库中的任何用户匹配一样简单。

    module.exports.checkFullName = (req, res, next) => {
        myCollection.findOne({ firstName: req.firstname, lastName: req.lastname },
            (err, user) => {
                if (!user)
                    return res.status(404).json({ status: false, message: 'User not found' });
                else
                    return res.status(200).json({ status: true,  user });
            }
        );
    }
    

    【讨论】:

      【解决方案3】:

      如果您使用的是最新的 mongodb 版本4.2

      ,您可以使用$regexMatch
      db.collection.find({
        "$expr": {
          "$regexMatch": {
            "input": { "$concat": ["$first", " ", "$last"] },
            "regex": "a",  //Your text search here
            "options": "i"
          }
        }
      })
      

      MongoPlayground

      【讨论】:

      • 非常好的答案,但唯一的问题是它适用于 4.2 版,但我在服务器上有 4.0
      • @HemantRajpoot 您可以轻松地将其更新到最新版本。它不会引发任何问题。
      • 由于服务器访问,我们不能做,它不是我们的客户端它的客户端
      • 救命答案
      【解决方案4】:

      如果您想使用聚合来做到这一点。这是一个例子

      db.user.aggregate(
         [
             {
                  $project : {
                      fullname: {$concat: ["$firstname", " ", "$lastname"]}
                  },
              },
              {
                  $match : {
                      fullname: "your full name"
                  }
              }
         ]
      )
      

      【讨论】:

      • 否,因为在 $match 管道中,查询正在执行完全相等的操作。但部分搜索也是可能的。像这样修改 $match 条件 $match : { fullname: {$regex: "firstname"}}
      猜你喜欢
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 2023-03-19
      • 1970-01-01
      • 2015-08-01
      相关资源
      最近更新 更多