mongodb:排序和限制集合,然后排序和限制结果文档嵌套文档

mongodb: order and limit the collection, then order and limit the resulting document nested documents

我的 game 集合中有以下数据结构:

{
    name: game1
    date: 2010-10-10
    media: [{
        id: 1,
        created: 2010-10-10 00:00:59
    }, {
        id: 2,
        created: 2010-10-10 00:00:30
    }]
},
{
    name: game2
    date: 2010-10-09
    media: [{
        id: 1,
        created: 2010-10-09 00:10:40
    }, {
        id: 2,
        created: 2010-10-09 09:01:00
    }]
}

我想获取具有最高日期的 game,然后获取具有最高 created 的相关 media 以获得其 ID。在上面的示例中,结果将是

{
    name: game1
    date: 2010-10-10
    media: [{
        id: 1,
        created: 2010-10-10 00:00:59
    }]
}

我尝试使用 findfind_one,以及 aggregation,但我想不出一种方法来进行此查询。

有什么建议吗?

您将需要 $unwind the media array in order to get the subdocument in that array where created is the highest then you $sort your documents by date and created all in descending order. Use $limit 输出 n 个文档,在我们的例子中是 1

In [26]: import pymongo

In [27]: conn = pymongo.MongoClient()

In [28]: db = conn.test

In [29]: col = db.gamers

In [30]: list(col.aggregate([{"$unwind": "$media"}, {"$sort": {"date": -1, "media.created": -1}}, {"$limit": 1}]))
Out[30]: 
[{'_id': ObjectId('553323ec0acf450bc6b7438c'),
  'date': '2010-10-10',
  'media': {'created': '2010-10-10 00:00:59', 'id': 1},
  'name': 'game1'
}]