gpt4 book ai didi

python-3.x - 按另一个字段 mongodb 查找不同的值组

转载 作者:可可西里 更新时间:2023-11-01 10:37:42 24 4
gpt4 key购买 nike

我收集了这样的文档:

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

不是 category_list by page_id 。

有什么帮助吗?

谢谢

最佳答案

你需要写一个聚合管道

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

关于python-3.x - 按另一个字段 mongodb 查找不同的值组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53830076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com