MongoDB Sorting Techniques

I'm struggling to figure out how to retrieve an ordered list from MongoDB data. I need to fetch the results from a Mongo collection using return and .find(), structured like this:

For instance, let's say I have one collection for cars with 10 documents:

//document structure:
{
  _id: 10,
  name: name,
  type: [suv, sedan, sport],
  driver: [object Driver]
  pubDate: new Date()
}

And then, I have another two collections for different types of drivers:

//document structure:
{
  _id: 20,
  name: name,
  type: stupid 'or' clever
}

Now, what I want is to return a list in a specific order, as shown below:

  1. name: Ford Focus, driver: {name: Nick, type: clever}, pubDate: 20:00;
  2. name: Nissan GTR, driver: {name: Andrew, type: clever}, pubDate:19:00;
  3. name: Jaguar xKR, driver: {name: John, type: clever}, pubDate:15:00;
  4. name: Honda Accord, driver: {name: Petr, type: clever}, pubDate:14:00
  5. name: Nissan GTR, driver: {name: Andrew, type: clever}, pubDate:13:00;
  6. name: Tesla, driver: {name: Jorge, type: stupid}, pubDate:20:00;
  7. name: Audi q7, driver: {name: Peggy, type: stupid}, pubDate:19:00;
  8. name: BMW 325, driver: {name: Minnie, type: stupid}, pubDate:18:00;
  9. name: CADILLAC, driver: {name: Timothy, type: stupid}, pubDate:16:00;
  10. name: SAAB, driver: {name: Julia, type: stupid}, pubDate:15:00;

Currently, I do have a solution in place, but it's not efficient and doesn't work well with infinite scroll. Using Meteor as an example:

// declare collections
Cars = Mongo.collection('cars', {
  name: name,
  type: [suv, sedan, sport],
  driver: [object Driver]
  pubDate: new Date()
}); 

Driver = Mongo.collection('cars', {
  name: name,
  lastName: lastName,
  type: stupid // or clever
}); 



// declare helpers for client:
Template.carList.helpers({
  'clever': function() {
     return Cars.find({driver.type: 'clever'}, {sort: {pubDate: -1});
     // returning only clever
   },
  'stupid': function() {
     return Cars.find({driver.type: 'stupid'}, {sort: {pubDate: -1});
     // returning only stupid
  }
 }):

In my HTML template using Blaze:

<template name='carList'>
     ...
      {{#each clever}}
        ...
      {{/each}}
      {{#each stupid}}
        ...
      {{/each}}
</template>

While this solution works, it lacks flexibility. If I need to add new sorting parameters, it becomes challenging. Furthermore, if driver types are stored in separate collections, such as Stupid & Clever, it complicates things even more.

I believe there must be a more elegant way to aggregate this data. What would you recommend? Thank you!

Answer №1

Have you considered passing the sort list to the helper and utilizing it to construct the sorting mechanism?

Here's a quick example that I came up with:

Template.carList.helpers({
  clever: function(sortField) {
    options = {};
    if (sortField) {
      options.sort = {sortField: -1};
    }
    return Cars.find({driver.type: 'clever'}, options);
  }
});

And in the HTML:

<template name='carList'>
     ...
      {{#each clever "name"}}
        ...
      {{/each}}
      {{#each stupid}}
        ...
      {{/each}}
</template>

You can make it a bit more intricate by passing key/value pairs, which Spacebars supports through Spacebars.kw. You could pass arguments like name=-1 pubDate=1, then in your helper, extract the resulting hash and incorporate them into your options. It may require some adjustments, but this should give you a good starting point.

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

The JMeter JSR223 Sampler and WebDriver Sampler do not support the Javascript language

I am currently working on integrating Selenium Webdriver Sampler with JMeter. Although I have been following tutorials, I have encountered an issue where the script language dropdown in the sampler screen does not include an option for JavaScript, prevent ...

maintaining the alignment of one div's right boundary with another div's right boundary

---------------------- ----------------------------->edge X | | | | | logo | | dropdown menu ...

What is the best method for globally configuring the Angular moment timezone?

I integrated angular moment js into my angular application. I am looking to display the date and time based on the time zone of the user accessing the app. However, I am facing difficulty in applying the time zone globally throughout my application. https ...

Can I update a label using ajax from the controller?

Hello everyone, I am facing a challenge in changing the text label coming from my Controller's JsonResult. There are two specific issues that I am encountering: 1) I am having difficulty displaying the text sent from my controller onto my view... ...

Transitioning from a fixed position to absolute in CSS3

Sticky Logo Element In my project, I implemented a logo element that is positioned absolutely within the document. As the user scrolls, the logo sticks to the top of the window with a fixed position (you can view an example here: https://jsfiddle.net/swzb ...

The NextJs image entered into an endless loop, throwing an error message that said: "The 'url' parameter is correct, but the response from the

I have been using next/image component with next js version ^12.2.3-canary.17 for my current project. The issue I am encountering is that some images are missing from the source directory, resulting in infinite error logs like the one shown below: https:/ ...

Encountering challenges with concealing a div element

As I'm setting up a table, I want to hide it immediately after creating it without affecting the DOM. Then, when the user selects from a dropdown menu, I show the table and everything works fine. However, the issue arises when I visit the page for the ...

Having trouble persisting data with indexedDB

Hi there, I've encountered an issue with indexedDB. Whenever I attempt to store an array of links, the process fails without any visible errors or exceptions. I have two code snippets. The first one works perfectly: export const IndexedDB = { initDB ...

Positioning the close button on the top right edge of a Material-UI Dialog: A step-by-step guide

https://i.sstatic.net/ARTtq.png How can I include a close icon in the top right corner of the header section? I'm using the Material UI Dialog and everything works well, but I need a close button in the top section. Can anyone assist me with this? ...

In Vue, props are not automatically assigned; be sure to avoid directly mutating a prop when assigning it manually to prevent errors

I am working with two Vue components: GetAnimal.vue and DisplayAnimal.vue. GetAnimal.vue sends a JSON object containing animal data to DisplayAnimal.vue using router push. DisplayAnimal.vue then displays this data. The process flow is as follows: I navigat ...

Using the Mousetrap binding on a nuxt.js page may not be effective

Hey there! I'm trying to achieve a certain functionality where I want to redirect to a different page once a specific sequence is typed. Although I can see the message "It works" in my console, the redirection is not happening and instead, I am gettin ...

Prevent automatic scrolling to the top of the page after submitting a form. Remain at the current position on the

After submitting a form, I want to prevent the page from automatically scrolling back up. How can I keep the same position on the page after form submission? <script type="text/javascript"> var frm = $('#form'); frm.submit(function ...

The path specified as "react-native/scripts/libraries" does not exist in the file

I've been troubleshooting an error on Github - https://github.com/callstack/react-native-fbads/issues/286. After cloning the repository and running it, I discovered that the error persisted. I am currently updating packages to investigate why this rec ...

Setting up Socket.io results in numerous transport polling GET requests being initiated

I have set up an express.js server-side and followed the socket.io guide. However, I am facing issues with the socket connection not being successful, and there seems to be a high number of unexpected GET requests like this: https://i.stack.imgur.com/GDGg ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

What causes Node.js to be unable to handle requests from Vue.js?

I'm encountering a strange error where Node.js is unable to see the URL address and consistently returns a 404 error. In my Vue.js application, I am making a post request using the axios package when the user clicks a button. The code snippet shows t ...

Is it possible to utilize a single Promise multiple times?

// App.js sites[site_name].search(value).then(function(results) { console.log(results); }); // SearchClass.js Search.prototype.search = function(search) { var self = this; this.params['wa'] = search; return new Promise(function ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Rapidly update code changes using the development mode in Next.js with the VS Code Remote Container/devcontainer

Struggling to enable Next.js' Fast Refresh feature while using a VS Code Remote Container. Running npm run dev displays the app on localhost, indicating the container functions properly - but Fast Refresh remains ineffective. Next.js version: v11.0.1 ...

Arranging numerous items based on date in JavaScript without prior knowledge

I'm facing an issue where I need to showcase JSON data containing events but want them sorted by time. The challenge is that the number of objects in the JSON can vary as users can keep adding more. Below is my code snippet demonstrating how the displ ...