Edmond Xie
Edmond Xie

Reputation: 21

mongoose find document with combined fields with one search parameter

I am using Nodejs and Mongodb with Mongoose. My model contains following properties:

first_name
last_name
status

I need to use mongoose find functions to search users with these 3 fields. I have 2 parameters:

full_name: Craig de Zia
status: alive

For example, I have a name called Craig de Zia. I don't know which parts of the name are first name or last name, so I want to search FULL name. And I want to connect full name and status with "$and" logic. The condition structure would be like:

'$and': [ 
    { 'full_name': 'Craig de Zia' },
    { status: 'alive' },
] 

The problem is that there is no full_name field in the database. We need to combine first_name field and last_name field. How can I do this?

Upvotes: 2

Views: 446

Answers (1)

Ashok
Ashok

Reputation: 2932

Manage first_name and last_name as per condition

db.collection.find({
  $and: [
    {
      $expr: { $eq: ['Craig de Zia', { $concat: ["$first_name", "$last_name"] }] }
    },
    { 'status': 'alive' }
  ]
})

Please manage first_name and last_name here $concat as "first_namelast_name" and if you want to search first_name and last_name with space in between them then use

{ $concat: ["$first_name", " ", "$last_name"] }

Upvotes: 2

Related Questions