2

I am trying to figure out how you would sort a collection by value where another value is == to something else see 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
      }
    ],
}
...
}

Say I have a collection of about 10 users whose services contain the serviceId xwY532yxcWQ7qAjuP I could find them using Meteor.users.find({ 'profile.services.serviceId' : service }); but if I wanted to sort the users by the their rate using Meteor.users.find({ 'profile.services.serviceId' : service }, , { sort: { 'profile.services.rate' : 1 } }); It sorts the users by who has the highest rate in any service not just xwY532yxcWQ7qAjuP So how would I go about sorting by rate where serviceId === xwY532yxcWQ7qAjuP ?

1 Answer 1

1

Sadly as far as I know, this is not really possible natively on MongoDB. You can probably make it work using the agreggate framework:

meteor add meteorhacks:aggregate

Then:

Meteor.users.aggregate([
         {$unwind:"$profile"},
         {$unwind:"$profile.services"},
         {$match:{"profile.services.serviceId":service}},
         {$sort:{"profile.services.rate":1}}
]);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer but I guess you cannot publish aggregations since they don't have cursors? I may have to change the way I am thinking about things and just make this part of the application non-reactive. Thank you for your time and help tho!
I don't know, the documentation says aggregate() returns a cursor...
Interesting I guess that is something they haven't added directly to meteor or to arunodas meteor aggregate then. View Issue
Yep, apparently it looks a little more complicated indeed... Good followup here, with good advice to look up for the counts-by-room example from the docs. I have to admit it seems to add quite some complexity

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.