0

I have a mongo collection that has docs similar to the schema below. And I have a ui from which a user could filter on the attributes (using logical or). Since its using OR I want the results to be ordered such that I first get the ones that match the most filters. For example: if i filter on author "auth1" and "tag1" I get back both records but the second record is on top. In this example I just have 2 attr to filter on, but there are about 20.

Do you have any suggestions of the best way of tackling this? I was thinking of writing a map-reduce query to compute the "match rank".

{name: "bookName", tags:["tag1"], authors: [] }
{name: "bookName2", tags:["tag1", "tag2"], authors: ["auth1", "auth2"] }
webber
  • 1,834
  • 5
  • 24
  • 56

2 Answers2

-1

If I understand your proble, You wants sort the result By authors.length and tags.length.

The problem, in MongoDB (I test on 2.6) with the sort(), it is impossible to sort by two parallels arrays. You can sort by album.length or tags.length but not both.

// sort By max to min authors
db.getCollection('rank').find({}).sort({ authors : -1 });
// sort by max to min tags
db.getCollection('rank').find({}).sort({ tags : -1 });

If you watn sort your result by both of them, you should use the Aggregation Framework. You have a great explanation here : https://stackoverflow.com/a/9040269/1506914

Community
  • 1
  • 1
throrin19
  • 17,796
  • 4
  • 32
  • 52
  • I wasnt trying to sort on the length of the arrays. I need to sort such that when I search for tag1 tag2 and auth1, i get back both of my records but bookname2 is on top as it matched on all 3 of the filters. Bookname1 would be at the bottom as it matched just tag1. Hope this makes more sense – webber Jun 24 '15 at 14:02
-1

It is possible using Aggregation Framework. Have a look at this question, it's similar to yours.

Community
  • 1
  • 1
Leffchik
  • 1,950
  • 14
  • 16