【问题标题】:Find distinct values group by another field mongodb通过另一个字段 mongodb 查找不同的值组
【发布时间】:2019-05-18 16:43:15
【问题描述】:

我收集了这样的文件:

{
    "_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"] 

不是 page_id 的 category_list 。

有什么帮助吗?

谢谢

【问题讨论】:

    标签: python-3.x mongodb distinct-values


    【解决方案1】:

    你需要编写一个聚合管道

    • $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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-16
      • 2019-01-14
      • 2021-06-27
      • 1970-01-01
      • 2015-08-17
      • 2012-01-23
      • 1970-01-01
      • 2018-06-30
      相关资源
      最近更新 更多