【问题标题】:Mongodb: Accessing a documents position in $projectMongodb:访问 $project 中的文档位置
【发布时间】:2014-12-17 16:32:00
【问题描述】:

如果我对聚合查询的结果进行排序,我可以访问结果中的文档位置吗?这将用于在 $project 内部执行计算,而不是返回结果并对其进行迭代。

文档位置为 0、1、2 等的期望结果:

db.trips.aggregate([
  { $match: { driver: "xx" } },
  { $sort: {  "start.time": -1 } },
  { $project: {
     _id: 1,
     driver: 1
     document_position: ____ 
  } }
])

【问题讨论】:

  • 我不认为你可以做你想做的事。您能否描述一下最终目标是什么?也许还有另一条通往最终目标的道路。

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您需要的是$limit$skip 管道阶段。使用它们您只能获取一系列记录,而无法从不连续的索引中挑选记录。

var fromindex = 1;  // define the index from which you want to pick the documents.
                    // Assuming index starts from 0.
var numberOfDocuments = 3; // The number of documents from the position.

db.trips.aggregate([
{$match:{"driver": "xx"}},
{$sort:{"start.time": -1}},
{$skip:fromindex-1},
{$limit:numberOfDocuments},
{ $project: {
     _id: 1,
     driver: 1
}
])

这将按排序顺序返回位置 1、2、3 的文档。

如果您看到,$project 阶段中​​没有文档位置。这不是必需的,因为您将按顺序获取结果并将其转换为数组并通过客户端的索引获取文档。

【讨论】:

    猜你喜欢
    • 2013-11-08
    • 2016-11-02
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多