Markus Hayner
Markus Hayner

Reputation: 2959

How to search for users's first name and last name in mongoDB and returning the full object

I want to search for my users in DB using their first name and last name and then returning the full object of it but what I've found in another post is returning the _id and name which is concatenated firstName and lastName

This is the code I am using.

results = await StageOne.aggregate([
      { $project: { "name": { $concat: ["$firstName", " ", "$lastName"] } } },
      { $match: { "name": { $regex: searchInput, $options: 'i' } } }
  ]).collation(
      { locale: 'en', strength: 2 }
  ).limit(limit).skip(offset);

And the response looks something like this

{ _id: 5f064921a8900b73174f76a1, name: 'John Doe' }

What I want to be returned is something like this

{ _id: 5f08fc3b8f2719096146f767, firstName: 'John', lastName: 'Doe', email: '[email protected]' ... createdAt: 2020-07-10T23:39:39.310Z, updatedAt: 2020-07-10T23:39:39.310Z, __v: 0 }

Which I can do it by running it like this separately for firstName or lastName

results = await StageOne.find({ firstName: { $regex: searchInput, $options: 'i' } }).collation(
        { locale: 'en', strength: 2 }
     ).limit(limit).skip(offset); 

Upvotes: 0

Views: 567

Answers (1)

Gibbs
Gibbs

Reputation: 22964

I would suggest you to add $project at the end of your pipeline.

{$project: {$firstName:1, $lastName:1, $email:1, $name:1}}

As In

 db.collection.aggregate([
  {
    $project: {
      "name": {
        $concat: [
          "$firstName",
          " ",
          "$lastName"
        ]
      },
      firstName: 1,
      lastName: 1,
      data: 1
    }
  },
  {
    $match: {
      "name": {
        "$regex": "ohn",
        "$options": "i"
      }
    }
  },
  {
    $project: {
      firstName: 1,
      lastName: 1,
      data: 1
    }
  }
])

play

You need to add part of your first project pipeline what are all the fields needs to be projected.

Another way to achieve this.

Upvotes: 1

Related Questions