Explore various queries and paths within MongoDB Atlas Search

I am currently working on developing an API that can return search results based on multiple parameters. So far, I have been able to successfully query one parameter.

For example, here is a sample URL:

http://localhost:3000/api/search?term=javascript&impact=sdg1

My goal is to get search results that meet both the conditions of term=javascript AND impact=sdg1

import Cors from "cors";
import initMiddleware from "../../util/init-middleware";
import { connectToDatabase } from "../../util/mongodb";

const cors = initMiddleware(
  Cors({
    methods: ["GET", "POST", "OPTIONS"],
  })
);

export default async function handler(req, res) {
  await cors(req, res);

  const { db } = await connectToDatabase();

 const data = await db
    .collection("jobs")
    .aggregate([
      {
        $search: {
          search: [
            {
              query: req.query.term,
              path: ["title", "role"],
            },
            {
              query: req.query.impact,
              path: ["impact"],
            },
          ],
        },
      },
    ])
    .sort({ date: -1 })
    .toArray();


  res.json(data);
}

I would like to know if it's feasible to achieve this and if anyone could recommend the appropriate type of query to use?

Thank you in advance

Answer №1

To achieve this, utilize the compound operator. Check out the documentation for more information and here is an example implementation in your code:

export default async function handler(req, res) {
  await cors(req, res);

  const { db } = await connectToDatabase();

 const data = await db
    .collection("jobs")
    .aggregate([
      {
        $search: {
          "compound": {
              "must": [{
                  "text": {
                      "query": req.query.term,
                      "path": ["title"", "role"],
                    }
                  }],
               "filter:"[{
                    "text": {
                      "query": req.query.&impact&,
                      "path": ["impact"],
                    }
                }]
           }
        },
      },
    ])
    .sort({ date: -1 })
    .toArray();


  res.json(data);
}

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

Sending a XML file from a Vue application to an ASP.NET Core backend using axios

I'm encountering difficulties when trying to upload an xml file using axios to my asp .net server. Below is the code snippet I am using on the vue side to retrieve and upload the xml file: uploadXmlFile(file: any) { const rawFile = new XMLHttpRequ ...

The error message "GetStaticPaths Error: Objects are not valid as a React child" indicates that an object was found when expecting a different type of data in a React component. To render a collection

I've encountered an issue while mapping the response from my get staticpath. Despite trying to destructure the response object, I haven't been successful. Consequently, when I select a single item, an error message is displayed. Feel free to chec ...

Challenges with JavaScript objects while using d3.js

I have been working on rendering a map using d3 within an HTML page that is running on a django web framework. One of the examples I came across from d3's sample archives can be found at this link: http://bl.ocks.org/NPashaP/a74faf20b492ad377312 Upon ...

Assign the values from the axios response to variables within the exported const

Currently, I am incorporating axios into my vue.js application to perform an HTTP POST request and retrieve some variables for a vue-echart. However, I have encountered a bit of a roadblock in determining the most effective approach. The snippet below is ...

Every time I attempt to retrieve target.value from the MUI datepicker in my Next.js project, I encounter an error

When I am using the MUI DatePicker component and try to access target.value, I encounter an error. You can see the error message here. Below is the code snippet: <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker className={Turn. ...

Limiting Ant Design Date range Picker to display just a single month

insert image description here According to the documentation, the date range picker is supposed to display two months on the calendar, but it's only showing one month. I carefully reviewed the documentation and made a change from storing a single va ...

Angular 4 after ejection, coupled with automated end-to-end testing using Protractor/Selenium setup

I am attempting to conduct end-to-end tests using Protractor/Selenium on an Angular 4 project that has been ejected. Here is my package.json: ... "scripts": { "pree2e": "webdriver-manager update --standalone false --gecko false --quiet node", "e2 ...

Exploring the benefits of refactoring jQuery promises in use cases

I've been thinking about how to optimize this pseudo-code: function foo() { if (condition) { return somethingReturningPromise().then(function (data) { doSomethingOnSuccess(data); return mainFunctionReturningPromise(); // he ...

Convert TypeScript-specific statements into standard JavaScript code

For my nextjs frontend, I want to integrate authentication using a keycloak server. I came across this helpful example on how to implement it. The only issue is that the example is in typescript and I need to adapt it for my javascript application. Being u ...

Transferring extensive PHP variables to JavaScript

After checking out different strategies for passing data from PHP to Javascript like this and this, I have concerns about the memory and variable size limits in javascript. Currently, I am transferring large chunks of HTML from PHP to Javascript to dynami ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...

Passing a variable to a different PHP script

I'm facing a dilemma and need some assistance. I'm encountering an issue where a PHP variable (or JavaScript/jQuery) is not being successfully transmitted to another PHP file through an AJAX request that I set up. To provide context, I am in the ...

Ways to retrieve the final appearance of element m in array n

As a beginner in programming, my goal is to access the last position of element m within array n. The following code displays all positions of element m: var n = []; while (true) { let input = prompt("Please enter a number for the ...

The placeholder text in the matInput field is not being displayed

As a newcomer to Angular, I am facing a challenge that has left me unable to find a solution. Below is the code snippet in question: <mat-form-field> <input matInput placeholder="ZIP" style="color:red;"> </mat-form-field& ...

Refresh Angular component upon navigation

I have set up routes for my module: const routes: Routes = [ { path: ":level1/:level2/:level3", component: CategoriesComponent }, { path: ":level1/:level2", component: CategoriesComponent}, { path: ":level1", component: ...

What is the reason behind the inability of this YouTube instant search script to enable fullscreen mode?

Looking to implement a Youtube instant search on my website, I came across this script that seems ideal for my needs. However, I'm facing an issue where the iframe is not displaying the allowfullscreen property. Can anyone assist with this problem? Th ...

Is anyone else experiencing issues with onSuccess and onError not functioning properly in the latest release of React-Query?

Issues are arising in the onSuccess and onError functions. After conducting some research, it appears that these functions have been deprecated in the latest version of React-Query. "use client" import { useRouter, useSearchParams } from 'n ...

Ways to retrieve the file name from the content-disposition header

I received a file through an AJAX response. I am trying to extract the filename and file type from the content-disposition header in order to display a thumbnail for it. Despite conducting multiple searches, I have been unable to find a solution. $(". ...

What is the reason the child component is not being displayed?

The code within the APP.js component looks like this: import React from "react"; import Exam from "./exam.js"; export default function App() { return ( <Exam> <h1>hashemi</h1> </Exam> ); } Similarly, the ...

Having trouble retrieving the URL from JSON data - every time I attempt to access it, it just shows as undefined. Any suggestions

Having trouble extracting the URL from JSON, as it shows undefined. Any suggestions? <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta> <script language="JavaScript" type="text/javascript" ...