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

Time:10-19

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!

CodePudding user response:

One option is using $ifNull:

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

See how it works on the playground example

  • Related