1

I have documents like below

{type: bacon, last_used: 1}
{type: fruit, last_used: 2}
{type: bread, last_used: 3}
{type: juice, last_used: 4}
{type: bacon, last_used: 5}
{type: juice, last_used: 6}

is it possible to sort on last_used AND also specify a value for the type field like bacon that should carry more weight and be listed first in results ?

So if someone really likes bacon they will always get bacon with last used on top but if they enter a unknown food type then they'll still get results.

I can think of client side ways to achieve but I want to do it server-side.

styvane
  • 59,869
  • 19
  • 150
  • 156
Flo Woo
  • 949
  • 1
  • 12
  • 26

1 Answers1

2

Based on this solution, you could use the following:

db.breakfast.aggregate([
   //$project is used to create a new field and select the desired fields between the existing ones.
   { $project: { 
         type: 1, 
         last_used: 1, 
         //This is the new field with a boolean value that helps with the ordering
         is_type: { $eq: ["$type", 'bacon'] } 
   }},  
   //Here one can select the ordering fields, first the one with more weight
   { $sort: { 
         is_type: -1,
         last_used: 1} 
   }])

This would return:

{ "_id" : ObjectId("57b484ff6472be59316fdde9"), "type" : "bacon", "last_used" : 1, "is_type" : true }
{ "_id" : ObjectId("57b484ff6472be59316fdded"), "type" : "bacon", "last_used" : 5, "is_type" : true }
{ "_id" : ObjectId("57b484ff6472be59316fddea"), "type" : "fruit", "last_used" : 2, "is_type" : false }
{ "_id" : ObjectId("57b484ff6472be59316fddeb"), "type" : "bread", "last_used" : 3, "is_type" : false }
{ "_id" : ObjectId("57b484ff6472be59316fddec"), "type" : "juice", "last_used" : 4, "is_type" : false }
{ "_id" : ObjectId("57b484ff6472be59316fddee"), "type" : "juice", "last_used" : 6, "is_type" : false }

Hope it helps!

Community
  • 1
  • 1
AxelWass
  • 1,321
  • 12
  • 21