【问题标题】:Mongoose - find documents with maximum no of countsMongoose - 查找具有最大计数的文档
【发布时间】:2015-10-29 06:50:53
【问题描述】:

我正在使用 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 属性并生成结果。有没有更好的方法来获得想要的结果。

【问题讨论】:

    标签: mongodb mongoose mean-stack mean.io


    【解决方案1】:

    这里只需要.sort().limit()

    Employee.find().sort({ "viewCount": -1, "name": 1 }).limit(5)
        .exec(function(err,results) {
    
    });
    

    这是在 viewCount 之后按名称排序的视图中排名前 5 位的员工。

    如果您希望它们在最后五个中按“名称”排序,那么只需对该结果进行排序:

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

    【讨论】:

    • { "viewCount": -1, "name": 1 } 条件背后的逻辑是什么。
    • @SharpCoder 答案中有一个指向.sort() 的链接,它告诉您这些是排序和排序顺序的关键。
    【解决方案2】:

    您可以按查看次数排序,并将搜索结果限制为 5 个。

    在代码中可能如下所示:

    Employee
    .find()
    .sort([['viewCount',-1], ['name',-1]])
    .limit(5)
    .exec(function(err, results){
      //do something with the results here
    });
    

    【讨论】:

      猜你喜欢
      • 2015-07-11
      • 2020-10-09
      • 1970-01-01
      • 2021-06-06
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 2012-01-19
      • 2021-05-15
      相关资源
      最近更新 更多