【问题标题】:Get position of object after sort in MongoDB在MongoDB中排序后获取对象的位置
【发布时间】:2016-08-17 07:00:56
【问题描述】:

我正在开发一个 Web 应用程序,并且我正在使用 MongoDB 来存储数据。我能够对数据进行排序并正确显示,但我想在使用 Mongo 排序后获取对象的位置。到目前为止,我有这个代码:

Websites.find({_id: {$lte: website_id}}, {sort:{upvotes: -1}}).count();

它并不完全有效。它返回某种位置,但与sort:{upvotes: -1} 无关。

那么,问题是,我怎样才能将1 退回到最高投票,2 退回到第二位,依此类推?

【问题讨论】:

  • 不太确定返回索引,但我很确定您可以使用 [Cursor])mongodb.github.io/node-mongodb-native/api-generated/cursor.html) 来完成您想要做的事情。
  • 你在做什么似乎没问题。我会尝试这样做:Websites.find({_id: {$lte: website_id}}, {sort:{upvotes: -1}}).fetch() 来调试它。
  • 那里为什么有count()方法?

标签: javascript mongodb sorting meteor


【解决方案1】:

你可以这样做。

<template name="websites">
  <h2>My Websites list</h2>
  <div class="row">
    {{#each websites}}
      Index:{{@index}}
      Feild1:{{feild1}}
      Feild2:{{feild1}}
      ...
    {{/each}}
  </div>
</template>

Template.websites.helpers({
  websites: function () {
    return Websites.find({_id: {$lte: website_id}}, {sort:{upvotes: -1}});
  },
  index: function (index) {
    return ++index;
  },
})

我没有创建任何表格或列表,但根据您的要求,您也可以添加它。 我希望干草能解决问题。

【讨论】:

    【解决方案2】:
    Websites.find({_id: {$lte: website_id}}, {sort:{upvotes: -1}}).fetch()
    

    【讨论】:

    • 仅代码通常不是一个好的答案 - 尝试添加解释,说明您认为这会解决问题的原因。
    猜你喜欢
    • 2012-01-30
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多