comebal
comebal

Reputation: 946

How to search firstname and lastname in mongodb

I read this article and saw how to search for the firstname of a record in mongodb:

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

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

but how do I search for the firstname and lastname given that my string has two words (which is the firstname and lastname).

In MySQL, I am using:

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

Where data contains "mike thompson".

Upvotes: 0

Views: 3362

Answers (2)

Brian Noah
Brian Noah

Reputation: 2972

This is my standard usage.

It uses the $or opperator.

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
    });
});

Upvotes: 0

Tyler Brock
Tyler Brock

Reputation: 30156

db.users.find({
    first_name: /^first/,
    last_name:  /^last/
})

Which means match a document where the first_name is equal to first AND the last_name is equal to last.

Upvotes: 0

Related Questions