0

I have a complex query using the aggregate framework and the $sort clause that results in a list of users in order from best to worst based on some criteria. Eg.

const result = [u1, u2, u3];

So that could be seen as:

User Rank
u1   1
u2   2
u3   3

I have a collection with fields user, location. I want to create a query such that I can append rank to the collection as part of the projection stage of the query:

User  Location UserRank
u1    China     1
u1    Brazil    1
u2    China     2
u3    Australia 3

and then group with min, to get:

Location BestUserRank
China     1
Brazil    1
Australia 3

which would be easy to do with min() in an aggregate function, but I don't know how to join those ranks to the query in the first place.

I feel like I should be able to do:

$project: {
  user: 1,
  location: 1,
  rank: { $rank: { field: '$user', dictionary: rankDictionary }
}

But from what I can tell, mongodb doesn't let you do anything like that.

  • 1
    No idea what you are saying. Much clearer if you show MongoDB documents, and what you actually expect to happen here. Writing "non-existant" pseudocode is not helping your case and is more likely to be interpreted as very little effort – Neil Lunn May 18 '18 at 08:41
  • The closest question is https://stackoverflow.com/questions/5681851/mongodb-combine-data-from-multiple-collections-into-one-how which is asking how to join two mongodb collections. I am kind of asking how to join a mongodb collection with a javascript object. It appears that I will have to use the same map reduce type of approach. –  May 18 '18 at 09:17

0 Answers0