我有像下面这样的文档
{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
字段指定一个值,如bacon,该值应该具有更大的权重并在结果中首先列出?
所以如果有人真的喜欢培根,他们总是会得到最后一次使用的培根,但如果他们输入未知的食物类型,他们仍然会得到结果。
我可以想到客户端实现的方式,但我想做的是服务器端
基于此解决方案,您可以使用以下命令:
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 }
希望有帮助!