gpt4 book ai didi

mongodb - 限制MongoDB `$bucketAuto`聚合阶段每个桶的输出

转载 作者:行者123 更新时间:2023-12-04 08:28:16 24 4
gpt4 key购买 nike

考虑具有以下文档的集合用户:

{"id": 1, "name": "John", "designation": "customer"}
{"id": 2, "name": "Alison", "designation": "manager"}
{"id": 3, "name": "Sam", "designation": "customer"}
{"id": 4, "name": "George", "designation": "salesperson"}
{"id": 5, "name": "Will", "designation": "salesperson"}
{"id": 6, "name": "Daffney", "designation": "customer"}
{"id": 7, "name": "Julie", "designation": "salesperson"}
{"id": 8, "name": "Elliot", "designation": "customer"}
{"id": 9, "name": "Bruno", "designation": "customer"}
{"id": 10, "name": "Omar", "designation": "customer"}
{"id": 11, "name": "Sid", "designation": "customer"}
{"id": 12, "name": "Nelson", "designation": "manager"}

在下面的操作中,输入文档根据designation字段中的值分为三个桶:

db.users.aggregate([
{
"$bucketAuto": {
groupBy: "$designation",
buckets: 5,
output: {
"count": { $sum: 1 },
"users" : {
$push: {
"name": "$name"
},
}
}
}
}
])

下面是这个操作的结果:

/* 1 */
{
"_id" : {"min" : "customer", "max" : "manager"},
"count" : 7.0,
"users" : [
{"name" : "John"},
{"name" : "Sam"},
{"name" : "Daffney"},
{"name" : "Elliot"},
{"name" : "Bruno"},
{"name" : "Omar"},
{"name" : "Sid"}
]
}

/* 2 */
{
"_id" : {"min" : "manager", "max" : "salesperson"},
"count" : 2.0,
"users" : [
{"name" : "Nelson"},
{"name" : "Alison"}
]
}

/* 3 */
{
"_id" : {"min" : "salesperson", "max" : "salesperson"},
"count" : 3.0,
"users" : [
{"name" : "George"},
{"name" : "Will"},
{"name" : "Julie"}
]
}

我想做的是将结果文档的“用户”属性中的结果数限制为 2,如下所示:

/* 1 */
{
"_id" : {"min" : "customer", "max" : "manager"},
"count" : 2.0,
"users" : [
{"name" : "John"},
{"name" : "Sam"}
]
}

/* 2 */
{
"_id" : {"min" : "manager", "max" : "salesperson"},
"count" : 2.0,
"users" : [
{"name" : "Nelson"},
{"name" : "Alison"}
]
}

/* 3 */
{
"_id" : {"min" : "salesperson", "max" : "salesperson"},
"count" : 2.0,
"users" : [
{"name" : "George"},
{"name" : "Will"}
]
}

有什么办法可以做到吗?

最佳答案

我不确定 $bucketAuto 是否可行,但您可以尝试 $slice 从数组和 $size 中获取有限的元素获取数组中元素的数量,

  • $bucketAuto阶段之后添加这个阶段,
  {
$addFields: {
users: { $slice: ["$users", 2] }
}
},
{
$addFields: {
count: { $size: "$users" }
}
}

Playground

关于mongodb - 限制MongoDB `$bucketAuto`聚合阶段每个桶的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65154220/

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