PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 20, 2022

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

 October 20, 2022     mongodb, mongoose, node.js     No comments   

Issue

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!


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



Answered By - nimrod serok
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing