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

Showing the date in AngularJSAngularJS can be used to

I have a view set up in AngularJS and I'm attempting to show the current date in a formatted way. My initial thought was to use <span>{{Date.now() | date:'yyyy-MM-dd'}}</span> to display the current date. ...

capturing the HTML title and storing it in a JavaScript variable

Is there a way to retrieve the title "Some Name" in the JS file and have it be populated by the hyperlink's title attribute, which is set to "sometitle" in the HTML code? JS var randomtext={ titleText:"Some Name",} HTML <a class="css" title="so ...

Limiting the usage of a command in Discord.js to one user at a time, rather than all users

I'm in the process of developing a discord.js bot and I need to implement a cooldown for a specific command. After searching several tutorials online, I found that most of them apply the cooldown to all commands (meaning all users have to wait a set ...

Unable to upload photo using Ajax request

I am in the process of trying to utilize Ajax to upload an image, so that it can be posted after the submit button is clicked. Here is the flow: User uploads image -> Ajax call is made to upload photo User clicks submit -> Post is shown to the user along ...

Unable to assign a boolean value to a data attribute using jQuery

I have a button on my page that has a special data attribute associated with it: <button id="manageEditContract" type="button" class="btn btn-default" data-is-allow-to-edit="@(Model.Contract.IsAllowToEdit)"> @(Model.Contract.IsAllowToEdit ? " ...

Automated tool for generating random JSON objects

Looking for a tool that can generate random JSON objects? I'm in need of one to test my HTTP POST requests and incorporate the random JSON object into them. Any recommendations? ...

The regex string parameter in node.js is not functioning properly for matching groups

The String.prototype.replace() method documentation explains how to specify a function as a parameter. Specifying a string as a parameter The replacement string can contain special patterns for inserting matched substrings, preceding and following portion ...

What is the order of reflection in dynamic classes - are they added to the beginning or

Just a general question here: If dynamic classes are added to an element (e.g. through a jQuery-ui add-on), and the element already has classes, does the dynamically added class get appended or prepended to the list of classes? The reason for my question ...

A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking ...

When a row is clicked, retrieve the data specific to that row

I have implemented a data-grid using react-table where I pass necessary props to a separate component for rendering the grid. My issue is that when I click on a particular row, I am unable to retrieve the information related to that row using getTrProps. ...

Tips on retrieving an input value from a dynamic list

I am struggling to retrieve the correct value with JavaScript as it always shows me the first input value. Any help would be greatly appreciated! Thank you in advance! <html> <head> </head> <body> <?php while($i < $forid){ ...

react-vimeo not firing onPause and onPlay events

I am facing an issue with triggering props when playing a Vimeo video on my webpage. Here's a snippet of my code: import Vimeo from '@u-wave/react-vimeo'; const handleVimeoProgress = (data: any) => { console.log('Progress:' ...

Utilizing unique layouts for specific views in sails.js and angular.js

I am currently working on a Sails.js + Angular.js project with a single layout. However, I have come across different HTML files that have a completely different layout compared to the one I am using. The layout file I am currently using is the default la ...

The Angular 1.x Ajax request is not triggering the expected update in the view

I am encountering an issue with my Angular application where the data retrieved from a JSON file is not updating in the view when the JSON file is updated. It seems like the JSON file and the view are out of sync. As a newcomer to Angular, I am struggling ...

The JSON response is being overridden by a catch-all URL and ends up being displayed as a 404 error page

I'm dealing with a React/Express setup that looks something like this (simplified for clarity): const path = require('path') const express = require('express') const CLIENT_BUILD_PATH = path.join(__dirname, '../build') ...

Renew Firebase Token

Currently, my email and password authentication flow in web Firebase JavaScript involves generating a token that I then verify on my node.js backend using firebase-admin. To make things easier, I store this generated token in the browser's local/sessi ...

Experiencing the AngularJS [$injector:modulerr] error message despite having flawless code

Despite having code that appears to be correct, I am consistently receiving an [$injector:modulerr] error when working with AngularJS. Check out the updated Fiddle here. I can't seem to figure out what the issue is. Could I be missing something obvi ...

Initiating an AJAX request to communicate with a Node.js server

Recently, I started exploring NodeJS and decided to utilize the npm spotcrime package for retrieving crime data based on user input location through an ajax call triggered by a button click. The npm documentation provides the following code snippet for usi ...

Using React to fetch data and then mapping it inside a function

I am facing an issue where I need to make a request for each item in the MAP, but I want to ensure that I wait for the response before moving on to the next object. Currently, my code is sending out all the requests simultaneously, causing the Backend to c ...

Using JavaScript to retrieve the updated timestamp of a file

Can JavaScript be used to retrieve the modified timestamp of a file? I am populating a webpage with data from a JSON file using JavaScript, and I want to display the timestamp of that file. Is there a way to do this using only JavaScript? ...