Retrieving specific items based on property and narrowing down a collection of objects using Mongoose

I'm currently developing a search feature that allows users to input a specific query and retrieve all messages containing that query.

The search process involves sending a query to the database based on the current message context when the user initiates the search.

Here is an example of the data structure returned by Messages.find():

const input = [
  {
      "_id": "1",
      "firstName": "John",
      "last_name": "Doe",
      "message_id": "12345",
      "messages": [
          {
              "time": "Thu Aug 05 2021 19:31:15 GMT-0700 (Pacific Daylight Time)",
              "text": "hey there"
          },
          ...
      ],
      "__v": 0
  },
  ...
]

In this scenario, I am looking to filter out only those items that contain the keyword "hey".


const expected = [
  {
      "_id": "1",
      "firstName": "John",
      "last_name": "Doe",
      "message_id": "12345",
      "messages": [
          {
              "time": "Thu Aug 05 2021 19:31:15 GMT-0700 (Pacific Daylight Time)",
              "text": "hey there"
          },
          ...
      ],
      "__v": 0
  },
  ...
]

The method I am currently using to achieve this involves iterating through the messages and filtering them based on the presence of the keyword "hey."

  Message.find({message_id})
    .then((messages) => {
      let filtered = messages.map(item => {
        let filteredMessages = item.messages.filter(message => {
          return message.text.toLowerCase().match(new RegExp("\\b" + "hey" + "\\b")) != null;
        });
        return {...item, messages: filteredMessages};
      }).filter(empty => empty.messages.length > 0);

Answer №1

Give this a shot...

db.collection.aggregate([
  {
    $match: {
      "messages.text": {
        "$regex": ".*hey.*"
      }
    }
  },
  {
    $unwind: "$messages"
  },
  {
    $match: {
      "messages.text": {
        "$regex": ".*hey.*"
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      messages: {
        "$addToSet": {
          time: "$messages.time",
          text: "$messages.text"
        }
      },
      "firstName": {
        $first: "$firstName"
      },
      "last_name": {
        $first: "$last_name"
      },
      "message_id": {
        $first: "$message_id"
      },
      
    }
  },
  {
    $sort: {
      _id: 1
    }
  }
])

Result

[
  {
    "_id": "1",
    "firstName": "John",
    "last_name": "Doe",
    "message_id": "12345",
    "messages": [
      {
        "text": "hey",
        "time": "Thu Aug 05 2021 19:37:15 GMT-0700 (Pacific Daylight Time)"
      },
      {
        "text": "hey there",
        "time": "Thu Aug 05 2021 19:31:15 GMT-0700 (Pacific Daylight Time)"
      }
    ]
  },
  {
    "_id": "2",
    "firstName": "Jane",
    "last_name": "Doe",
    "message_id": "12345",
    "messages": [
      {
        "text": "hey buddy",
        "time": "Thu Aug 05 2021 19:32:15 GMT-0700 (Pacific Daylight Time)"
      }
    ]
  }
]

Check it out on mongoplayground

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

How can I save the indexed directory to a variable using Node.js?

What is the best way to index a directory in nodeJS and save it as a variable? I haven't made any attempts yet, so I'm not sure where to start with the code. ...

What is causing the constant failure of the httpr.send() method?

I had a similar code running before, but unfortunately, I seem to have lost it. Despite trying different approaches, the PHP code just won't execute. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8& ...

What is the best way to repair a react filter?

Recently, I successfully created a database in Firebase and managed to fetch it in React. However, my current challenge is to integrate a search bar for filtering elements. The issue arises when I search for an element - everything functions as expected. ...

What is the best way to include a context in a JavaScript promise?

Figuring out JS Promises has always been a challenge for me. I'm aware this might be a basic question, but please bear with me. =) Looking at the code snippet below, my goal is to modify a property within the class containing this function (essentiall ...

Chrome is experiencing a problem with anchor tags that have an href attribute set to a "blob:" URL and using a target of "_blank"

My current project involves developing a website feature that allows users to download a PDF version of a page. To achieve this, the generated HTML is rendered into a PDF on the server, which is then returned as a Base64-encoded PDF. This data is converted ...

What is the correct method for calculating the sum of one input field and multiple output fields?

I have a single input field and multiple calculated output fields using JavaScript :Click here to view the screenshot of the calculated problem You can see the live preview on this link: . When you visit this link, enter "Base on your annual bill amount: ...

"Discovering the value of an object when the key is not a string but you have been provided with a string key to locate

How can I retrieve the value of an object when its key is not a string, but I am given a string to search for the value? Example: let obj={ arr: ["Kapil"]}; Find the value of obj.arr when you are given 'arr' as a key. I tried ...

Can mouseenter and mouseleave events be implemented in Chart.js?

Currently, I am using the onHover function on each pie to implement some scale/zoom effect. However, I would like to switch to using mouseenter and mouseleave. When there is a mouseenter event on a pie, it should enlarge with scale/zoom effect, and when th ...

Tips for completing the loading process before the child process finishes executing in node.js

My experience with node.js is still in its early stages. I currently have a setup where a child process is triggered to run a .jar file when I access http://localhost:4000/testjar. The page takes a while to load and only displays the output after the child ...

Creating an array of objects sorted in alphabetical order

My task involves working with an array of objects that each have a name property: var myList = [{ name: 'Apple' }, { name: 'Nervousness', }, { name: 'Dry' }, { name: 'Assign' }, { name: 'Date' }] ...

Encountering an incorrect number of parameters for "undefined" during the deployment of a smart contract

I am facing an issue while attempting to deploy my first Voting contract on the testRPC. The error seems to arise from the arguments parameter in the code snippet below. When I tried passing an empty array, it gave an error stating "Got 0 expected 1!". Si ...

leveraging the situation and a clever opening

Currently, I'm diving into mastering the proper utilization of context and hooks. Initially, everything worked flawlessly while all components remained within a single class. However, troubles arose when I segregated them into multiple classes leading ...

Task: Choose MySQL option and Retrieve JSON data

I have a question regarding implementing a function in a separate module file and calling it within a route to retrieve query data: function getSobre() { return new Promise((resolve, reject) => { db.query(`SELECT * FROM sobre ORDER BY cod ...

Sorting an array of strings based on user input using Vue.js

I'm facing an issue where I have an array of various strings: [ "Aluminum", "Basic Materials", "Broad Credit", "Broad Market", "Cocoa", "Coffee", "Consumer Cyclicals", "Consumer Non-cyclicals", "Copper", "Corn", "Cotton", "Crude Oil", "Energy", "Exte ...

Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a spec ...

"Combine JSON data using an observable based on the ID field

Consider two distinct REST services in my project: todo.service.ts user.service.ts Below are the properties defining each object: todo: userId, title, id, completed user: id, name, email, etc Both services return an Observable with collections conformi ...

The deprecation of the componentWillReceiveProps lifecycle method in React components is posing challenges for developers utilizing

I am faced with a dilemma involving 2 components: one is responsible for adding new posts to an array of existing posts, while the other component maps through this array to display them on the page. My goal is to add the new post to the beginning of the ...

The PKIJS digital signature does not align with the verification process

Explore the code snippet below const data = await Deno.readFile("./README.md"); const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate; const privateKey = (await loadPEM("./playground/domain-pk ...

Troubleshooting issue with file upload feature in Angular for Internet Explorer 9

I have implemented a file upload method using the following code: <input type="file" name="upload-file" ng-model= "excelFile" accept=".xlsx" onchange="angular.element(this).scope().fileChanged(this);" ...

Incrementing and decrementing a textbox value by one using onClick

I'm looking for help with a JavaScript solution without using jQuery or any plugins, specifically for Cordova/PhoneGap. I am new to JavaScript and learning as I go, so please bear with me. My goal is to create a functionality where there is a textbox ...