Extract data from an array in MongoDB by organizing it into sections based on dates

As a beginner in the world of MongoDB, I'm trying to figure out how to extract data from an array in separate sections.

{
   "name":"User name",
   "messages":[
      {
         "message":"Message 1",
         "date":"2022-05-12T00:00:00.000Z"
      },
      {
         "message":"Message 2",
         "date":"2022-05-12T00:00:00.000Z"
      },
      {
         "message":"Message 3",
         "date":"2022-05-13T00:00:00.000Z"
      },
      {
         "message":"Message 4",
         "date":"2022-05-13T00:00:00.000Z"
      },
      {
         "message":"Message 5",
         "date":"2022-05-13T00:00:00.000Z"
      }
   ]
}

The desired outcome that I'm aiming for is

[
   {
      "date":"2022-05-12T00:00:00.000Z",
      "messages":[
         {
            "message":"Message 1",
            "date":"2022-05-12T00:00:00.000Z"
         },
         {
            "message":"Message 2",
            "date":"2022-05-12T00:00:00.000Z"
         }
      ]
   },
   {
      "date":"2022-05-13T00:00:00.000Z",
      "messages":[
         {
            "message":"Message 3",
            "date":"2022-05-13T00:00:00.000Z"
         },
         {
            "message":"Message 4",
            "date":"2022-05-13T00:00:00.000Z"
         },
         {
            "message":"Message 5",
            "date":"2022-05-13T00:00:00.000Z"
         }
      ]
   }
]

I haven't had much exposure to MongoDB aggregation yet and while I've searched through numerous queries on stack overflow, none have provided me with the assistance I need.

Is there a way to achieve this? If so, I would greatly appreciate any guidance. :)

Answer №1

To achieve the desired result, consider using aggregation in your query.

db.collection.aggregate([
  {
    $unwind: "$entries"
  },
  {
    $group: {
      _id: "$entries.timestamp",
      entries: {
        $push: "$entries"
      }
    }
  },
  {
    $project: {
      _id: 0,
      timestamp: "$_id",
      entries: 1
    }
  }
])

Answer №2

  1. $unwind - Breaking down the messages array into multiple documents.
  2. $group - Grouping by messages.date and including the messages document in the messages array.
  3. $project - Customizing the output documents.
db.collection.aggregate([
  {
    $unwind: "$messages"
  },
  {
    $group: {
      _id: "$messages.date",
      messages: {
        $push: "$messages"
      }
    }
  },
  {
    $project: {
      _id: 0,
      date: "$_id",
      messages: 1
    }
  }
])

Try out the Sample Mongo Playground

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

Having trouble with my AJAX request and can't figure out why. Anyone available to take a look and help out?

I have successfully implemented this AJAX script on various pages in the past without any issues. <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript" src="jquery.validate.min.js"></script& ...

Guide on sending a JavaScript variable to PHP using AJAX

I am currently utilizing the following JavaScript code to obtain data from a td element when a button is clicked within an onclick event. function rfk(element) { var element = element.parentElement.parentElement; var id = parseInt(element.childre ...

Navigating asynchronous URL parsing in NodeJS

I am still fairly new to the world of Node.js and Javascript, so I appreciate your patience with my confusion around the callback mechanism Bacchanalia. The Issue at Hand I'm currently working on a basic Node.js application that is responsible for h ...

What is the best way to incorporate raw HTML code into a .jsx file within a NextJS website?

I need to integrate Razorpay code into my NextJS website, but it's currently in pure HTML format. For example, the code looks like this: <form><script src="https://cdn.razorpay.com/static/widget/subscription-button.js" data-subscrip ...

The function in jQuery that can be used to hide a <div> when clicked

I am facing a problem with my jQuery code that is supposed to remove/hide a specific div. Despite checking various examples, I can't seem to make it work properly. This issue arises in the context of jQuery on Drupal 7. The live site where this proble ...

Is there a way to determine if npm packages are accessing and misusing my system's environment variables?

Apologies if this seems nonsensical. But including a code snippet like this: // to illustrate I'm utilizing a source from https://www.npmjs.com/package/got got.post(maliciousUrl, {json: process.env}) Is it enough to leak environment variables to an u ...

Guarantee the successful execution of a server-side function using my client-side function

I am currently in the process of creating a website that utilizes Javascript and Asp.net. My code contains numerous functions on the client side, within my html code, while my server side functions are called using a webservice. How can I ensure that my c ...

Removing a key from an index signature in Typescript - a step-by-step guide

In my web application built with Angular, we encountered a need for a data type to store translations of strings in different languages. To address this requirement, a team member defined the following type: export class TranslatedString { [language: str ...

The installation of package.json is unsuccessful, as it will only proceed with an empty name and version

Having trouble installing the package.json file after updating to the latest version of Node on my Windows PC. When trying to run npm, an error was thrown. Any help would be greatly appreciated. Command Prompt C:\Users\Felix\Desktop\ ...

Populate tabulator table with nested data fetched through an ajax call

I received an API response from a store in JSON format containing three records at the first level. The structure of the response includes data, error_no, msg fields. Within the data field at the second level, I have data.items, data.total_pages, data.to ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...

When working with MongoDB, I often encounter the need to efficiently query large amounts of data. To improve response time, I frequently consider whether to create compound indexes or single

Within my project, there exists a post collection with the following schema: posts:{ title: {type: String, required: false}, text: {type: String, required: false}, plainDescription: {type: String, required: f ...

The length of the scope variable generates an error

var example = $scope.newgoal.gTitle; console.log(example.length); Even running this short code test, it throws an error message: TypeError: Cannot read property 'length' of undefined I've attempted to find various solutions without succes ...

Display or conceal a field depending on the user's input

I need to display a checkbox only when the firstname matches abc or if the email is [email protected]. var x = abc; //will be dynamic var y = abc @gmail.com jQuery("#firstname").on('change', (function(avalue) { return function(e) { ...

What method can be used to incorporate Google Places API into a .js file without using a <script> element?

As I delve into the Google Places API documentation, I noticed that they require the API be loaded in this format: <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script> Is ...

Difficulty arises when attempting to locate particular information within a Vue component using a method that is contained within the component

Currently, I am in the process of developing a request management system for the organization. The key requirements for this project include: Ability to add a new row for each new request. Dynamic generation of parameters based on the selected descriptio ...

Failure occurred when attempting to link and display on the page container

I have created a simple app using jQuery Mobile. At some point in the app, I include the following code: <a href="test_es.html" data-role="button">Start!</a> This code snippet loads a new HTML file that contains several jQuery Mobile page ...

Change URL link after login user with javascript

Is there a way to generate a URL link based on the user's name (gmail)? For example: The code below is somewhat suitable for my needs. However, I am trying to figure out how to automatically retrieve the username and populate it in the input field. ...

A PHP tag containing a div element

As someone who is new to web development, I have a question that may seem silly to some. I am familiar with adding div tags inside php tags, but I am unsure if it's possible to add onclick functions or any other type of function to these div tags. He ...

The 'load()' event method in jQuery does not function properly within the 'ready()' event method on mobile browsers

After testing on Firefox mobile and Chrome mobile browsers, I found that my code works perfectly on computer browsers. Below is the code I have inside the ready() and load() event methods: $(document).ready(function(){ $(window).on('load hashchan ...