Searching for a user's first name and last name in mongoDB and retrieving the entire object

My goal is to locate my users in the database by searching for both their first and last names, and then retrieving the complete object of each user. However, my current code only returns the concatenated `firstName` and `lastName` as `name` along with the `_id`.

Here is the code I am working with:

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

After executing the code, the response I receive is in the format:

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

What I actually want is the complete user object like this:

{ _id: 5f08fc3b8f2719096146f767, firstName: 'John', lastName: 'Doe', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="39535651575d565c">[email protected]</a>' ... createdAt: 2020-07-10T23:39:39.310Z, updatedAt: 2020-07-10T23:39:39.310Z, __v: 0 }

To achieve this, I would need to execute separate queries for `firstName` and `lastName` like this:

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

Answer №1

To improve your pipeline, I recommend adding the $project stage at the end.

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

For example:

 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
    }
  }
])

Try it out here

Be sure to include all the necessary fields in your first project pipeline for projection.

Another approach for achieving the same result.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Elements overlapped with varying opacities and responsive to mouse hovering

In this Q/A session, we will explore a JS solution for managing the opacity of overlapping elements consistently during hover. Objective Our goal is to create two transparent and overlapping elements, similar to the red boxes showcased below. These eleme ...

Troubleshooting GLSL scripts within a web-based WebGL environment

Are there ways to debug GLSL code or display variable values directly from within the GLSL code when using it with WebGL? Does three.js or scene.js offer any features for this purpose? ...

ReactJS does not recognize the library mentioned

click here to access the pondjs folder inside node-modulesAfter installing pondjs(https://www.npmjs.com/package/pondjs) using npm install pondjs --save in my react application and confirming its presence in package.json, I encountered an issue in App.js. W ...

An issue is encountered with the JavascriptExecutor while attempting to navigate to a different page using Selenium Webdriver

My goal is to capture user actions such as clicks, keypress, and other DOM events by adding JavaScript event listeners to the WebDriver instance. Everything works fine until I navigate to the next page, where I encounter an exception due to an undefined fu ...

Flashing bug in the outFunction of jquery hover()

My friends and I are working on a website for a class project, but we're running into a strange issue with the outFunction part of our hover function. Whenever the mouse hovers over an element, a grey square fades in using .fadeIn(), but then immediat ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

What is the best way to halt execution in Express.js following an error caught from an Await request?

While searching for a solution, I come across many posts that almost provide the answer I need, but nothing seems to quite work in my case. I have a function that uses asynchronous operations: const doStuff = async (data)=>{ if(data == "a bug& ...

Performing API requests in NextJS using Prisma on a client-side page

Currently, I am faced with a challenge in fetching data from my database on a NextJS page designated as a client page using "use client" as required by the theme I am working with. At the moment, I have a page that fetches data from the database and redire ...

A guide to displaying a PDF preview using React Dropzone

I am struggling to find a way to display previews of PDF files that I'm uploading using react-dropzone. Although PNG and JPG files are working correctly, I would like to be able to show the user either the actual PDF or an image representation of it. ...

Exploring AngularJS: A Guide to Accessing Millisecond Time

Is there a way to add milliseconds in Time using AngularJS and its "Interval" option with 2 digits? Below is the code snippet, can someone guide me on how to achieve this? AngularJs Code var app = angular.module('myApp', []); app.controller(&ap ...

Personalized parallax design

I am in the process of developing my own custom parallax plugin to allow me to control the direction in which items transition off the screen. However, I am currently facing a challenge in ensuring that regardless of how a user scrolls or the size of the w ...

Exploring logfile usage in JavaScript. What is the best way to structure the log?

Currently, I am developing a Python program that parses a file and records the changes made to it. However, I am facing a dilemma regarding the format in which this information should be saved for easy usage with JavaScript on the local machine. My objecti ...

"Troubleshooting: Why are errors not appearing in ts-node

Whenever I encounter an error in my code while compiling with ts-node, the error does not seem to appear in the console. For instance:let data = await fs.readFileSync(path); In the following code snippet, I am using "fs" to read a file by passing a path ...

How can I stop full-page auto-scroll screenshot extensions from automatically scrolling?

As the owner of a membership website, I'm faced with the challenge of preventing users from easily taking full page screenshots of the valuable text content in my members area. Many browser extensions, such as Fireshot and GoFullPage, enable auto-scro ...

When attempting to install font-awesome with meteor npm, the module 'fontawesome'" was not found

Currently working with meteor version 1.4.1.1 which has NPM support enabled. I encountered an issue after installing the npm package "font-awesome" where the console displayed an error message stating "Uncaught Error: Cannot find module 'fontawesome&a ...

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...

Ways to switch text on and off smoothly using transitions

I have created a webpage where text starts off hidden but has a visible heading. When you click on the heading, the text is revealed below. I am putting the final touches and aiming to make the text slide in smoothly. I am using Javascript for toggling ins ...

When filling options within an optgroup in a selectbox, the data for each option may override one another

UPDATE: I made a change in my code: $('select[name=productSelect]').setOptions(["All products|ALL", "Products visible to all|VISIBLETOALL=1"]); I updated it to: $('select[name=productSelect]').prepend(["All products|ALL", "Product ...

Is it possible to conditionally call the Apollo Client in my Vue template script?

I have a scenario where I pass a query to the apollo client in my template file using a script tag. However, I want to find a more efficient way to handle this without having to specify the query every time. My idea is to pass a boolean value through a pro ...

Issues with Rock Paper Scissors Array in Discord.js V12 not functioning as expected

I'm currently working on implementing an RPS game in my Discord bot. I want to create a feature where if the choice made by the user doesn't match any of the options in the list, it will display an error message. Here is the code snippet that I h ...