Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get full name from first, middle, last name and search among the result for a match?

I have a collection as

[
  {
    firstName: "John",
    middleName: "F",
    lastName: "Kennedy"
  }, 
  {
    firstName: "Barack",
    lastName: "Obama"
  }
]

I am trying to create a function that searches the collection by name. I need to concat the names before trying to find a match. I tried the following

User.aggregate([
  {
    "$project": {
      fullName: {
        "$concat": [
          "$firstName",
          " ",
          "$lastName"
        ]
      }
    }
  },
  {
    $match: {
      "fullName": {
        $regex: /[a-z\\s]*oba[a-z\\s]*/i
      }
    }
  }
])

It works for names without middle names. But I need this to work for names with middle names too. When I try to concat middleName, I get an error because the path middleName does not exist on all documents. I could not implement $cond and $exists operators properly make this work. Any kind of help is highly appreciated. Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option is using $ifNull:

db.collection.aggregate([
  {$project: {
      fullName: {$concat: [
          "$firstName",
          " ",
          {$ifNull: [
              {$concat: ["$middleName", " "]},
              ""
          ]},
          "$lastName"
      ]}
  }}
])

See how it works on the playground example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading