Locate every instance of items in an array within a string

My files have a structure similar to this:

https://i.stack.imgur.com/KyaVY.png

When a user conducts a search, they send an array to the backend. This array always includes at least one element.

For example, if they send ['javascript'] to the backend. Is there a method to query MongoDB to identify which documents contain the term javascript?

I attempted something like,

db.find({ body: { $all:['javascript'] } });

However, this only functions if body is also an array. Are there any other ways to achieve this?

Answer №1

One way to search for multiple keywords in a text is by creating a pipe-delimited regex pattern with the list of keywords like so:

const words = ["react", "node", "angular"];
const regexPattern = words.join("|");

db.find({
  body: { $regex: regexPattern, $options: 'i' }
});

Answer №2

To utilize the $regex operator, simply include a regex within a string:

db.find({ content: { $regex: ".*python.*" }});

Alternatively, you can use the following methods:

db.find({ content: /.*python.*/ });
db.find({ content: /python/ });

Answer №3

To begin, the first step is to establish a text index on the specific fields you wish to search within. If your intention is to search across all fields in the collection, simply execute the following command:

db.collection.createIndex( { "$**": "text" } )

If you only want to search within certain designated fields, then utilize this format instead:

db.collection.createIndex( { title: "text", body: "text" } )

You also have the option to assign weightage to the fields, such as giving more importance to 'title' over 'description'.

Subsequently, conduct your searches using the syntax below:

db.collection.find( { $text: { $search: "java javascript python" } } )

This query will retrieve documents containing any or all of the specified words: java, javascript, or python.

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

Leveraging the Spread Operator in Redux mapDispatchToProps with SweetAlert2

When I add the swal action creators to the mapDispatchToProps function like this: function mapDispatchToProps(dispatch) { return { getAnimal: (_id) => dispatch(getAnimal(_id)), ...swal } } The issue aris ...

Issues are arising with Jquery Scripts when running through Selenium in IE 9, resulting in the error message SCRIPT5009: '$' is undefined. However, these scripts are functioning correctly when executed directly in the web browser

While using Selenium, the code below is causing issues as it is not functioning properly. An error SCRIPT5009: '$' is undefined is being thrown in IE 9. However, if the code is executed in a web browser console after removing the "\" sign, i ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

Explore flat data querying using Firebase and AngularFire

I am working with data stored in firebase, utilizing a flat structure with key-value pairs to establish a many-to-many relationship between events and users (see figure 1). While it's straightforward to look up events associated with a user using pure ...

The battle between CSS and jQuery: A guide to creating a dynamic zebra-style table without relying on additional plugins

Is there a better way to create a dynamic zebra styling for table rows while still being able to hide certain elements without losing the styling? In this code snippet, I'm using the CSS :nth-of-type(even) to style even rows but running into issues wh ...

Tips on adjusting a JavaScript animation function

I'm currently working on adjusting the animation function within the "popup" class that controls the gallery section of a website. When the page loads, an image and background start expanding from zero scale in the center to 100 VIEWPORT HEIGHT (VH) a ...

Javascript - When I preview my file, it automatically deletes the input file

My form initially looked like this : <form action="assets/php/test.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> ...

switching the image source by selecting different options from a dropdown menu and leveraging JavaScript

I have been attempting to change the src of an image using JavaScript's addEventListener, but for some reason it is not working. Here is an example to illustrate my issue: let bulbImage = $.querySelector(".bulb-image"); let turnOnOption = $.querySele ...

Tips for stopping slide transition (moving to a different slide) in vue-slick-carousel?

I'm utilizing vue-slick-carousel to populate schedule data for a specific slide (in this case, a month). <vue-slick-carousel @afterChange="afterChange" @beforeChange="beforeChange" @swipe="swipe" class="te ...

Enhanced Search and Replace Techniques in HTML using jQuery and JavaScript

Although I have some experience with jQuery and Javascript, I am by no means an expert. I have been struggling to find a way to achieve my goal using minimal resources. Maybe you can assist me: This is what I am trying to accomplish: I would like to use ...

Utilizing Core-TransitionEnd in Polymer: A Beginner's Guide

After a ripple animation on an item has executed, I would like to run a function. Currently, I am using the following code: <post-card id="card1"> <img width="70" height="70" src="../images/start.png"> <h2>P ...

What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

What could be causing the state to not update as anticipated?

I am currently in the process of developing a TicTacToe game and have a requirement to maintain the current player in state under the name currentPlayer. The idea is that after one player makes a move, I need to update currentPlayer to represent the opposi ...

Executing a time-consuming function call within the componentDidMount lifecycle method of a React component

When working with my React component, I utilize the componentDidMount function to pass a string received through props to a processing function. This function then returns another string which is used to update the component's state. import React, { C ...

What is the maximum duration we can set for the Ajax timeout?

I am facing a situation where an ajax request can take between 5-10 minutes to process on the server side. Instead of continuously polling from JavaScript to check if the request is completed, I am considering making just one ajax call and setting the tim ...

What is the best way to retrieve web pages from the cache and automatically fill in form data when navigating to them from different pages on my website?

On my website, I have multiple pages featuring forms along with breadcrumbs navigation and main navigation. Interestingly enough, the main navigation and breadcrumbs share some similarities. However, my desire is that when users click on breadcrumb links, ...

Discover the nearest class and smoothly expand it with the slideDown function in jQuery

Hey there, I'm working on implementing a "View More" button on my page. The button will reveal another unordered list that currently has the class of "hidden-list". When the user clicks on "View More", I want it to slideToggle the hidden-list element ...

Customize the appearance of each element in ng-repeat individually

In my code, I have implemented an ng-repeat. Each alternate div inside the ng-repeat is supposed to have a different border-color, which is achieved by using the following structure: <div ng-repeat="channel in channelList"> <div ng-style="get ...

Determine if a mobile application has been installed using Vue.js

I am currently developing a web application and have implemented a check to determine whether the user is accessing it from a mobile device or laptop. Let's consider the link as: my-site.com In addition to the web version, my site also offers a mobi ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...