Mongo复杂的群体

时间:2013-09-10 13:04:11

标签: mongodb

我有这个系列:

{
        "_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吗?

1 个答案:

答案 0 :(得分: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"
  }
});