gpt4 book ai didi

mongodb - 仅在 MongoDB 中满足特定条件时分组

转载 作者:行者123 更新时间:2023-12-04 15:06:09 25 4
gpt4 key购买 nike

如果组事件的数量超过 3,我想通过它们的 pid(仅组)对一些特定记录进行分组。

示例:

此处group (pid: 200)的事件数为4,必须分组。

- Events -
----------
{_id: ObjectId, type: 'private', pid: 140, data: {...}},
{_id: ObjectId, type: 'group', pid: 800, data: {...}}, // << group 800
{_id: ObjectId, type: 'group', pid: 200, data: {...}}, // << group 200
{_id: ObjectId, type: 'group', pid: 200, data: {...}}, // << group 200
{_id: ObjectId, type: 'private', pid: 140, data: {...}},
{_id: ObjectId, type: 'group', pid: 200, data: {...}}, // << group 200
{_id: ObjectId, type: 'group', pid: 200, data: {...}}, // << group 200
{_id: ObjectId, type: 'private', pid: 130, data: {...}},

此处对group (pid: 200)进行了分组,并将is_too_long: true添加到记录中。并且 group (pid: 800) 没有按预期分组。

- Results -
-----------
{_id: ObjectId, type: 'private', pid: 140, data: {...}},
{_id: ObjectId, type: 'group', pid: 800, data: {...}, is_too_long: false}, // << group 800
{_id: ObjectId, type: 'private', pid: 140, data: {...}},
{_id: ObjectId, type: 'group', pid: 200, is_too_long: true}}, // << group 200 (with [is_too_long: true])
{_id: ObjectId, type: 'private', pid: 130, data: {...}, is_too_long: false},

我尝试了其他一些查询,但都没有用!请帮助我!

最佳答案

  • $facet 分隔privategroup 文档,
  • $grouppid 和数组中的文档分组
  • $cond 检查条件,如果分组文档大于或等于 3,则从数组中切出单个元素并设置 is_too_long: true 否则为 false
  • $map 迭代 docs 数组的循环并放入 bool 属性 is_too_long
  • $unwind 解构root数组
  • $replaceRootroot 对象替换为 root
  • $concatArrays,连接privategroup数组
  • $unwind 解构root数组
  • $replaceRoot 替换根中的root对象
db.collection.aggregate([
{
$facet: {
private: [{ $match: { type: "private" } }],
group: [
{ $match: { type: "group" } },
{
$group: {
_id: "$pid",
root: { $push: "$$ROOT" }
}
},
{
$project: {
root: {
$cond: [
{ $gte: [{ $size: "$root" }, 3] },
{
is_too_long: true,
docs: { $slice: ["$root", 1] }
},
{
is_too_long: false,
docs: "$root"
}
]
}
}
},
{
$project: {
root: {
$map: {
input: "$root.docs",
in: { $mergeObjects: ["$$this", { is_too_long: "$root.is_too_long" }] }
}
}
}
},
{ $unwind: "$root" },
{ $replaceRoot: { newRoot: "$root" } }
]
}
},
{ $project: { root: { $concatArrays: ["$private", "$group"] } } },
{ $unwind: "$root" },
{ $replaceRoot: { newRoot: "$root" } }
])

Playground

关于mongodb - 仅在 MongoDB 中满足特定条件时分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66076492/

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