Ranjith
Ranjith

Reputation: 2819

How to find a document where either one or another field matches a value?

My model was,

var userSchema = new Schema({
    first_name : String,
    last_name : String,
    ...
});

From this, I need to do search filter option. For that I am passing name params with value.

Now I want to return the document which contains first_name == name or last_name == name

How to write the query for that?

Upvotes: 2

Views: 1643

Answers (1)

Mattias Farnemyhr
Mattias Farnemyhr

Reputation: 4238

User.findOne({
    $or: [
        {first_name: name},
        {last_name: name},
    ],
}, function(err, user) {
    ...
})

Use find if you expect there to be more than one document matching name to be equal to first_name or last_name.

Upvotes: 7

Related Questions