Mongoose - 查找具有最大计数的文档
Mongoose - find documents with maximum no of counts
我正在使用 Mongoose 从 MongoDB 获取数据。这是我的模型。
var EmployeeSchema = new Schema({
name: String,
viewCount: { type: Number, default: 0 },
description: {
type: String,
default: 'No description'
},
departments: []
});
我需要找到 count(viewCount) 按姓名排序最高的前 5 名员工。
我正在考虑使用 find() 查找所有员工,然后读取 viewCount 属性 并生成结果。有没有更好的方法可以得到想要的结果。
Employee.find().sort({ "viewCount": -1, "name": 1 }).limit(5)
.exec(function(err,results) {
});
这是在 viewCount 之后按姓名排序的观看次数中排名前 5 位的员工。
如果您希望它们在最后五个中按 "name" 排序,那么只需对该结果进行排序:
Employee.find().sort({ "viewCount": -1, "name": 1 }).limit(5)
.exec(function(err,results) {
// sort it by name
results.sort(function(a,b) {
return a.name.localeCompare(b.name);
});
// do something with results
});
您可以按观看次数排序并将搜索结果限制为 5 个。
在代码中可能如下所示:
Employee
.find()
.sort([['viewCount',-1], ['name',-1]])
.limit(5)
.exec(function(err, results){
//do something with the results here
});
我正在使用 Mongoose 从 MongoDB 获取数据。这是我的模型。
var EmployeeSchema = new Schema({
name: String,
viewCount: { type: Number, default: 0 },
description: {
type: String,
default: 'No description'
},
departments: []
});
我需要找到 count(viewCount) 按姓名排序最高的前 5 名员工。
我正在考虑使用 find() 查找所有员工,然后读取 viewCount 属性 并生成结果。有没有更好的方法可以得到想要的结果。
Employee.find().sort({ "viewCount": -1, "name": 1 }).limit(5)
.exec(function(err,results) {
});
这是在 viewCount 之后按姓名排序的观看次数中排名前 5 位的员工。
如果您希望它们在最后五个中按 "name" 排序,那么只需对该结果进行排序:
Employee.find().sort({ "viewCount": -1, "name": 1 }).limit(5)
.exec(function(err,results) {
// sort it by name
results.sort(function(a,b) {
return a.name.localeCompare(b.name);
});
// do something with results
});
您可以按观看次数排序并将搜索结果限制为 5 个。
在代码中可能如下所示:
Employee
.find()
.sort([['viewCount',-1], ['name',-1]])
.limit(5)
.exec(function(err, results){
//do something with the results here
});