按一个字段排序,但保持另一个字段始终在结果之上

时间:2016-08-17 15:09:43

标签: mongodb mongodb-query aggregation-framework

我有以下文件

{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}

是否可以对last_used进行排序并指定type字段的值,如培根应该承载更多的重量并在结果中首先列出?

所以,如果有人真的喜欢培根,他们总会在最后一次使用培根时获得培根,但如果他们进入未知的食物类型,那么他们仍会得到结果。

我可以想到客户端实现的方法,但我想在服务器端做到这一点。

1 个答案:

答案 0 :(得分:2)

根据this解决方案,您可以使用以下内容:

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} 
   }])

这将返回:

{ "_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 }

希望它有所帮助!