我有一个这样的文档结构:
[
{
"country": "UK",
"shops": [
{"city": "London", "fruits": ["banana", "apple"]},
{"city": "Birmingham", "fruits": ["banana", "pineapple"]},
],
},
{
"country": "DE",
"shops": [
{"city": "Munich", "fruits": ["banana", "strawberry"]},
{"city": "Berlin", "fruits": ["kiwi", "pineapple"]},
],
},
]
在我的python脚本中,我有一个dict将每个水果Map到一个类别值:
categories = {
1: ["apple"],
2: ["banana", "kiwi"],
3: ["pineapple", "strawberry"]
}
已确认输出:
现在,我想使用mongo聚合框架,为每个文档获取max_category,它是根据categoryMap从shops子文档中找到的max值投影出来的。
[
{
"country": "UK",
"shops": [
{"city": "London", "fruits": ["banana", "apple"]},
{"city": "Birmingham", "fruits": ["banana", "pineapple"]},
],
"max_category": 3
},
{
"country": "DE",
"shops": [
{"city": "Munich", "fruits": ["banana", "apple"]},
{"city": "Berlin", "fruits": ["kiwi", "apple"]},
],
"max_category": 2
},
]
谢谢你的帮助!
2条答案
按热度按时间5w9g7ksd1#
你的category dict不适合mongo,因为mongo要求对象的键是字符串类型。您可以将dict转换为下面的形式以便于处理:
在聚合管道中,通过
$reduce
遍历wrangled category数组,有条件地更新累加器,以获得最大匹配类别。Mongo Playground
ryevplcw2#
另一种选择是计算它,而不重新展开和分组:
$reduce
、$map
和$filter
:了解它在playground example上的工作原理