如何在Mongodb上对数据进行排序

时间:2017-05-14 05:32:52

标签: javascript arrays node.js mongodb

以下是来自MongoDB的数据

{
  "urls" : {
    "beauty-credit" : {
      "count" : 1,
      "keyword" : "beauty credit",
      "last_res" : 152,
      "last_sea" : "Sat May 13 2017 15:16:41 GMT+0700 (SE Asia Standard Time)",
      "url_site" : "beauty-credit"
    },
    "etude" : {
      "count" : 2,
      "keyword" : "etude",
      "last_res" : 1048,
      "last_sea" : "Sat May 13 2017 15:16:38 GMT+0700 (SE Asia Standard Time)",
      "url_site" : "etude"
    },
    "skinfood" : {
      "count" : 2,
      "keyword" : "skinfood",
      "last_res" : 478,
      "last_sea" : "Sat May 13 2017 15:16:45 GMT+0700 (SE Asia Standard Time)",
      "url_site" : "skinfood"
    }
  }
}

这是我的代码。现在我只过滤last_res> 10

function gotData(data){
        result = data.val() 
        const urls_kws = Object.keys(result)
                        .filter(key => result[key].last_res > 10)
}

如何按"计数"?对数据进行排序?另外我怎么才能显示30行?

1 个答案:

答案 0 :(得分:0)

为了按计数对数据进行排序,您可以使用javascript中的sort()函数和自定义比较器,例如

 urls_kws.sort((a, b) => a.count - b.count)

为了现在只获得前30个值,您可以切片数组

 var short_urls_kws = urls_kws.slice(0, 30)