如何查找在日期范围内发送的前3个文档?

时间:2019-08-08 19:06:19

标签: mongodb aggregation-framework pymongo

我使用MongoDB来存储用户消息。通过使用聚合框架,我想根据邮件的日期过滤邮件,并找到答复数最高的前3条邮件。

我为许多用户提供了以下JSON结构:

[
  {
    "u_name": "Erdem",
    "details": {
      "messages": [
        {
          "m_type": "text",
          "m_date": 1565208272.547057,
          "m_content": "Sentence",
          "m_replied": 0
        },
        {
          "m_date": 1565208362.439494,
          "m_content": "Another Sentence",
          "m_replied": 50
        }
      ]
    }
  },
  {
    "u_name": "Tolga",
    "details": {
      "messages": [
        {
          "m_type": "text",
          "m_date": 1565201272.547057,
          "m_content": "Sentence",
          "m_replied": 0
        },
        {
          "m_date": 1565208322.439494,
          "m_content": "Another Sentence",
          "m_replied": 14
        }
      ]
    }
  }
]

我尝试了以下汇总操作,以过滤出指定日期范围内的邮件,并找到m_replied计数最大的前3条邮件。

db.collection.aggregation(
[                                                                        
  {'$unwind' : "$details.messages" },                                                             

  {'$match': {'$and': [{'details.messages.m_date':{'$gte': 1564949580}},                          
                {'details.messages.m_date':{'$lte': 1664949580}}]}},                                                                                        
  {'$group': {'_id': '$u_name','s_msg': {'$max': '$details.messages.m_replied'}}},  

  {'$project': {'_id': 0,'u_name': '$_id','s_msg': 1}},                   

  {'$sort': {'s_msg': -1}},                           

  {'$limit': 3}                                                                                                                                                                                                   
]
)

但是,此查询不会返回具有最大m_replied个条目的消息。有人可以帮助我找到正确的查询吗?

1 个答案:

答案 0 :(得分:1)

以下查询可以为您提供预期的输出:

db.collection.aggregate([
    {
        $unwind:"$details.messages"
    },
    {
        $match:{
            "details.messages.m_date":{
                $gte:1564949580,
                $lte:1664949580
            }
        }
    },
    {
        $sort:{
            "details.messages.m_replied":-1
        }
    },
    {
        $limit:3
    },
    {
        $project:{
            "_id":0
        }
    }
]).pretty()

输出:

{
    "u_name" : "Erdem",
    "details" : {
        "messages" : {
            "m_date" : 1565208362.439494,
            "m_content" : "Another Sentence",
            "m_replied" : 50
        }
    }
}
{
    "u_name" : "Tolga",
    "details" : {
        "messages" : {
            "m_date" : 1565208322.439494,
            "m_content" : "Another Sentence",
            "m_replied" : 14
        }
    }
}
{
    "u_name" : "Erdem",
    "details" : {
        "messages" : {
            "m_type" : "text",
            "m_date" : 1565208272.547057,
            "m_content" : "Sentence",
            "m_replied" : 0
        }
    }
}