【问题标题】:How to search firstname and lastname in mongodb如何在mongodb中搜索名字和姓氏
【发布时间】:2013-05-23 09:32:05
【问题描述】:

我读了这篇文章,看到了如何在 mongodb 中搜索记录的名字:

http://docs.mongodb.org/manual/reference/sql-comparison/

db.users.find({ firstname: /^bc/ });

但是鉴于我的字符串有两个单词(即名字和姓氏),我如何搜索名字和姓氏。

在 MySQL 中,我使用的是:

SELECT * FROM profiles WHERE match(firstname, lastname) AGAINST ('".$data."');

其中数据包含“mike thompson”。

【问题讨论】:

  • 就像 MySQL 一样,你需要选择一个通用的分隔符来分隔名字和姓氏。 MySQL 使用 ` `(空白空间)并且将在输入的 AGAINST 数据上执行与 PHP 中的 list() 相同的操作。因此,要在 MongoDB 中执行此操作:list($first,$last)=explode(' ',$data); $mongo->users->find(array('firstname'=>new MongoRegex($first),'lastname'=>new MongoRegex($last)))

标签: php sql mongodb


【解决方案1】:
db.users.find({
    first_name: /^first/,
    last_name:  /^last/
})

这意味着匹配 first_name 等于 first 且 last_name 等于 last 的文档。

【讨论】:

    【解决方案2】:

    这是我的标准用法。

    它使用 $or 运算符。

    var query = req.query.query,
        queryArr = query.split(' '),
        first_name,
        last_name;
    // Check if it is split into a first and last name
    if (queryArr.length === 2) {
        //create regex for first and last name
        first_name = new RegExp(queryArr[0], 'i');
        last_name = new RegExp(queryArr[1], 'i');
    }
    query = new RegExp(query, 'i');
    var dbQuery = {
        // Searches first_name or last_name
        $or: [
            {
                // Searches first name based on whole query or first_name query
                $or: [
                        {
                        first_name: query
                    },
                    {
                        first_name: first_name
                    }
                ]
            },
            {
                // Searches last_name based on whole query or last_name query
                $or: [
                    {
                        last_name: query
                    },
                    {
                        last_name: last_name
                    }
                ]
            }
        ]
    };
    db.users.find(dbQuery, function (error, response) {
        res.send(200, {
            success: true,
            body: response
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-01-19
      • 2018-09-02
      • 1970-01-01
      • 2016-09-28
      • 2011-08-19
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多