在MongoDB中按另一个字段分组查找不同的值

5

我有一个包含如下文档的集合:

{
    "_id" : ObjectId("5c0685fd6afbd73b80f45338"),
    "page_id" : "1234",
    "category_list" : [  
        "football", 
        "sport"
    ],
    "time_broadcast" : "09:13"
}

{
    "_id" : ObjectId("5c0685fd6afbd7355f45338"),
    "page_id" : "1234",
    "category_list" : [ 
        "sport",
        "handball"
    ],
    "time_broadcast" : "09:13"
}

{
    "_id" : ObjectId("5c0694ec6afbd74af41ea4af"),
    "page_id" : "123456",
    "category_list" : [ 
        "news", 
        "updates"
     ],
     "time_broadcast" : "09:13"
}

....

now = datetime.datetime.now().time().strftime("%H:%M")

我希望的是:当“time_broadcast”等于“now”时,获取每个“page_id”的不同“category_list”列表。
以下是输出的格式要求:
{
   { 
     "page_id" : "1234",
     "category_list" : ["football", "sport", "handball"] 
   },

   { 
     "page_id" : "123456",
     "category_list" : ["news", "updates"] 
   }
}

我试过像这样做:
category_list = db.users.find({'time_broadcast': now}).distinct("category_list")

但是这会给我输出不同值的列表,但是包括所有“page_id”的值:
 ["football", "sport", "handball","news", "updates"] 

无法通过页面 ID 进行分类列表。

请求帮助!

谢谢。

1个回答

5

您需要编写一个聚合管道

  • $match - 根据条件筛选文档
  • $group - 按键字段对文档进行分组
  • $addToSet - 聚合唯一元素
  • $project - 以所需格式投影
  • $reduce - 通过 $concatArrays 减少数组的数组为数组

聚合查询

db.tt.aggregate([
    {$match : {"time_broadcast" : "09:13"}}, 
    {$group : {"_id" : "$page_id", "category_list" : {$addToSet : "$category_list"}}}, 
    {$project : {"_id" : 0, "page_id" : "$_id", "category_list" : {$reduce : {input : "$category_list", initialValue : [], in: { $concatArrays : ["$$value", "$$this"] }}}}}
]).pretty()

结果

{ "page_id" : "123456", "category_list" : [ "news", "updates" ] }
{
        "page_id" : "1234",
        "category_list" : [
                "sport",
                "handball",
                "football",
                "sport"
        ]
}

如果需要,您可以通过page_id管道添加$sort


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接