0

If I have these two objects:

OBJECT A:

{
  ...,
  votes: {
    claps: [{ count: 10, }, { count: 5 }],
    hearts: [{ count: 5 }, { count: 2 }]
  }
}

OBJECT B:

{
  ...,
  votes: {
    claps: [{ count: 20 }, { count: 10 }],
    trophy: [{ count: 5 }]
  }
}

For instance, object A has a total of 22 votes, and object B has 35 votes.

I already have a function that, given an object, gets its total number of votes.

I also already have a compare function which returns 1 if greater, 0 if equals, and -1 if less than.

But it seems to me that Mongo's sort doesn't support giving it a compare function.

How would I go about sorting these type of objects in Mongo?

prasad_
  • 12,755
  • 2
  • 24
  • 36
padowbr
  • 31
  • 1
  • 3
  • What is the sorting criteria? – D. SM Jan 27 '21 at 01:25
  • @D.SM sorry, if an item has a > number of votes it should be placed first – padowbr Jan 27 '21 at 01:41
  • Use aggregation pipeline, $set with $size, then $sort. – D. SM Jan 27 '21 at 02:43
  • In case you have MongoDB v4.4, you can use the [$function](https://docs.mongodb.com/manual/reference/operator/aggregation/function/index.html) to sort the array using an aggregation query. With earlier versions (v4.2 or less), you can try something like in this post: [Mongodb sort inner array](https://stackoverflow.com/questions/15388127/mongodb-sort-inner-array). Also, note there are quite a few posts out on the net... – prasad_ Jan 27 '21 at 04:11

0 Answers0