0

我有这个收藏:

{
        "_id" : ObjectId("522f05f06f92046814003b84"),
        "personal_id" : "0609150071",
        "superstructure_id" : 1,
        "name" : "David",
        "surname" : "Bar",
        "plays_often" : 1,
        ...
        "created" : ISODate("2013-09-10T13:43:38Z")
}
{
        "_id" : ObjectId("522f05f06f92046814003b84"),
        "personal_id" : "0609150071",
        "superstructure_id" : 1,
        "name" : "David",
        "surname" : "Bar",
        "plays_often" : 1,
        ...
        "created" : ISODate("2013-09-10T14:11:55Z")
}
...

并需要查找记录:

  • 标准:superstructure_id: 1

  • 分组依据personal_id

  • 从这些组中仅返回基于created字段的最新记录

  • 然后对所有组结果进行排序plays_often

  • 有限制 5

所以结果将只有这条记录,"personal_id" : "0609150071"因为在created

{
        "_id" : ObjectId("522f05f06f92046814003b84"),
        "personal_id" : "0609150071",
        "superstructure_id" : 1,
        "name" : "David",
        "surname" : "Bar",
        "plays_often" : 1,
        ...
        "created" : ISODate("2013-09-10T14:11:55Z")
}

这在mongodb中可能吗?

4

1 回答 1

1

结果将不包含整个原始文档。相反,它包含一个doc_id字段,该字段是_id原始文档的字段。最终$project操作员将重命名某些字段以匹配输入文档。例如,$group运算符重命名personal_id_id,因此$project将其改回。

db.goalie_tables.aggregate({
  // Only select documents where superstructure_id = 1
  $match: {
    superstructure_id: 1
  }
}, {
  // Sort the documents for each personal_id in descending created date order
  $sort: {
    personal_id: 1,
    created: -1
  }
}, {
  // Select the first document (ie, most recently created) for each personal_id
  $group: {
    _id: "$personal_id",
    doc_id: {
      $first: "$_id"
    },
    plays_often: {
      $first: "$plays_often"
    }
  }
}, {
  // Sort the results by plays_often (descending)
  // Change to 1 for ascending
  $sort: {
    plays_often: -1
  }
}, {
  // Limit to 5 documents
  $limit: 5
}, {
  // Rename fields:
  //   _id => personal_id
  //   doc_id => _id
  //   plays_often => plays_often
  $project: {
    _id: "$doc_id",
    personal_id: "$_id",
    plays_often: "$plays_often"
  }
});
于 2013-09-10T15:40:56.377 回答