Sorting a collection based on an array value in Meteor JS

I'm currently facing the challenge of sorting a collection based on a specific value while another value is equal to something else. Please refer to the document below:

{
  "_id": "zLFp8KptxzACGtAZj",
  "createdAt": "2015-05-28T21:11:57.044Z",
...
  "profile": {
    "firstname": "Nelle",
    "lastname": "Carroll",
...
    "services": [
      {
        "serviceId": "Gy7uptfk8LNWMgEQy",
        "rate": 19
      },
      {
        "serviceId": "KvFETNLK8cJ78e6gy",
        "rate": 1
      },
      {
        "serviceId": "xwY532yxcWQ7qAjuP",
        "rate": 42
      }
    ],
}
...
}

Let's say I have a collection of around 10 users, and I want to sort them by rate for those whose services include the serviceId xwY532yxcWQ7qAjuP. I can locate them using

Meteor.users.find({ 'profile.services.serviceId' : service });
. But if I wish to order the users by their rates using
Meteor.users.find({ 'profile.services.serviceId' : service }, , { sort: { 'profile.services.rate' : 1 } });
, it will arrange them based on the highest rate across all services, not just for xwY532yxcWQ7qAjuP. How can I achieve sorting by rate where serviceId equals xwY532yxcWQ7qAjuP?

Answer №1

Unfortunately, to my knowledge, it seems that performing this task directly on MongoDB is not feasible. One potential solution could involve leveraging the aggregate framework:

meteor add meteorhacks:aggregate

Subsequently, you can execute the following code:

Meteor.users.aggregate([
         {$unwind:"$profile"},
         {$unwind:"$profile.services"},
         {$match:{"profile.services.serviceId":service}},
         {$sort:{"profile.services.rate":1}}
]);

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

What possible reasons could explain why certain AngularJS code only functions properly when the Internet Explorer console is actively open

Encountering a peculiar issue with an AngularJS controller (2 way data binding issue using IE 11 with AngularJS). Strangely, the problem seems to resolve itself when I have the debugging tools open in IE 11. Any insights on why this could be happening and ...

Occasionally, the NodeJs server will freeze up and require a forced stop via ctrl+c to

My node.js server is set up to handle ajax requests. When I click on the webpage, an ajax call is sent and the function runs smoothly most of the time. However, there are instances where the server freezes. In some cases, using ctrl+c unfreezes it and it c ...

Tips for increasing a cell in AG Grid React table:

Just starting out with the AG Grid library and encountering issues when updating the cells. To simplify, I will describe my problem using basic numbers instead of dates. Start is set to 1. Stop value is already established. End needs to be determined. Dur ...

Initiating a horizontal scroll menu at the center of the screen: Step-by

I need assistance setting up a horizontal scrolling menu for my project. The requirement is to position the middle button in the center of the .scrollmenu div. Currently, I am working with HTML and CSS, but open to suggestions involving javascript as well ...

Setting a variable equal to user input

When using a jQuery script, the elements for the details are dynamically created inside a jQuery function. However, there seems to be an issue with assigning the value from the variable "startLocation" to the input "detail_startLocation[]". Only the firs ...

Merging dynamic fields array into a unified object in MongoDB

In my Mongo collection, I have the following data: { "_id" : ObjectId("62aeb8301ed12a14a8873df1"), "Fields" : [ { "FieldId" : "e8efd0b0-9d10-4584-bb11-5b24f189c03b", "Value&q ...

Updating embedded documents in arrays in MongoDB can be achieved by following these steps

I am working with the following document: {_id: '4eb79ee1e60fc603788e7259', Name: 'name', Subsidiaries: [ { _id: '4eb79eeae60fc603788e7271', Location: 'location1'}, { _id: 'subid2', Location: &a ...

The ngx-mat-intl-tel-input plugin is experiencing issues with functionality within the Angular 17 framework

I am currently using Angular 17 and here are the specific Versions/Details: Angular CLI: 17.3.8 Node: 18.20.2 Package Manager: npm 10.5.0 OS: linux x64 Angular: 17.3.12 My goal is to import the ngx-intl-tel-input library in order to validate phone numbers ...

Retrieve a specific object property from an array of values

My MongoDB collection is structured like this: { "_id": 123, version: 2, property: "toenail", options: [ {"color": "blue", age: "15"}, {"color": "black", age: "27"} ] }, { "_id": 124, version: 12, property: ...

Is JavaScript Promise Chaining Allowed?

I have a question regarding my code, despite it currently functioning correctly. Specifically, I'm wondering if the sequence of promises in my database is valid. Promise 1 must be fulfilled before moving on to Promise 2 because I rely on the data and ...

Retrieving complete database in JSON format with the help of the mysql node.js driver

Currently, I am working on developing a JavaScript file to extract a JSON dump from an entire MySQL database that is running on the server side. I have successfully found and implemented the MySQL driver for node.js for executing queries. While the process ...

Make a JSONP request with the MIME Type set to text/plain

I've been attempting to utilize JSONP for fetching a feed from a different domain. Despite knowing that the content type should ideally be JSON or JavaScript, it is currently set as text/plain and unfortunately, I lack control over the server settings ...

Is there a workaround for unresolved symlink requirements when using npm link?

Creating an NPM package often involves using the following: npm link This allows for making modifications to a package called <myPackage> during development without constantly having to publish and unpublish! Developers can make changes locally and ...

What can be done to prevent unnecessary API calls during re-rendering in a React application?

On my homepage, I have implemented code like this: {selectedTab===0 && <XList allItemList={some_list/>} {selectedTab===1 && <YList allItemList={some_list2/>} Within XList, the structure is as follows: {props.allItemList.map(ite ...

Jest remains verdant even in cases where Expected does not match Received

it('User is already present as a supplier', (done) => { const store = mockStore({}, [{ type: 'get_user', data: { } }]); return store.dispatch(userGetAction({ role: 'supplier' }, () => {})).then(() => { t ...

Incorporate various variables within a JavaScript loop

I have a range of input classes from .fat-calc1 to .fat-calc24, as well as a designated result area with the class fat-result. My goal is to create a loop that accumulates all inputs (.fat-calc1 + .fat-calc2 + ... + .fat-calc24) and presents the sum in the ...

Tips for utilizing various broadcast options to trigger Angular controllers according to the user's chosen selection

I'm currently developing an angularjs application that includes multiple date range pickers on a single web page. When a user selects a date range from one of these pickers, I need to send the selected dates to the corresponding angular controller ass ...

Interacting with react-virtualized: accessing Grid's public functions

Trying to utilize the public method recomputeGridSize on a Grid component that I am currently rendering. I have set up the ref, but when attempting to call the method, it seems like it is not accessible. Outlined below is where the ref is established with ...

A step-by-step guide on extracting nested ASP.NET DataGrid values with JavaScript

Looking to retrieve data from a nested data grid on an aspx page using JavaScript. Check out the following code snippet: <tr> <td colspan="2" align="center"> <asp:DataGrid ID="sampleData" AutoGenerateColumns="false" runat="serv ...

Create automatic transcripts for videos, including subtitles and captions

Are there any tools or plugins available that can automatically create a transcript of a video for website playback? For example, generating captions and subtitles in the English language. ...