我有一个具有以下结构的集合(我将发布一个游乐场的链接,因为它很大):
https://mongoplayground.net/p/WNga0mze0WS
只是一个简短的解释,我们正在寻找
materias
(主题)和 assuntos
(主题),并且我们希望该聚合返回具有 3 次或更多 nomes
的
erros
(该主题的名称)数组(错误)比
acertos
(正确),这样我们就可以显示学生需要更好地掌握哪些主题。其他结果并不重要,只要是3次或以上即可。
我想创建一个对
user.uid
进行分组的聚合,因为在此集合中,您可以获取其他用户的结果,并尝试根据主题名称添加所有错误和正确答案 (assuntos.nome
)。
到目前为止我已经尝试了很多事情,但这是我尝试的最后一件事:
db.aggregate([
{ $unwind: "$materias" },
{ $unwind: "$materias.assuntos" },
{
$group: {
_id: {
_id: "$user.uid",
nome: "$materias.assuntos.nome",
total: "$materias.assuntos.total",
acertos: "$materias.assuntos.acertos",
erros: "$materias.assuntos.erros",
// sumErro: {
// $sum: {
// "$toInt": "$materias.assuntos.erros"
// }
// },
teste: {
// $sum: {
"$cond": {
"if": {
"$and": [
{
"$gte": [
"$materias.assuntos.erros", 3
]
},
{
"$gte": [
"$materias.assuntos.erros",
{ $multiply: [ "$materias.assuntos.acertos", 3 ] }
]
}
]
},
"then": "$materias.assuntos.erros",
"else": "$$REMOVE",
}
// }
}
},
},
},
{
$group: {
_id: {
_id: "$_id._id",
nome: "$_id.nome",
erros: "$_id.erros",
teste: "$_id.teste"
},
}
}
])
我还尝试仅按 uid 和 materias.assuntos.nome 进行分组,然后再分组以获得结果,但无法成功。我在那里做的条件是我正在寻找的错误比 acertos 多 3 倍,而且我认为错误也需要是 3 或更多。
我预计一个结果至少有超过 3 个错误,但我做错了一些事情,因为它没有根据主题名称添加这些值。
如果需要,我还可以提供另一份文档,因为我发送的文档只有 1 个主题,其错误比 acertos 多 3 倍。
如有任何帮助,我们将不胜感激
我通过在操场上工作找到了这样的解决方案
db.collection.aggregate([
{
$unwind: "$materias"
},
{
$unwind: "$materias.assuntos"
},
{
$group: {
_id: {
user: "$user.uid",
nomeAssunto: "$materias.assuntos.nome"
},
total: {
$sum: "$materias.assuntos.total"
},
acertos: {
$sum: "$materias.assuntos.acertos"
},
erros: {
$sum: "$materias.assuntos.erros"
}
}
},
{
$group: {
_id: "$_id.user",
assuntos: {
$push: {
nome: "$_id.nomeAssunto",
total: "$total",
acertos: "$acertos",
erros: "$erros"
}
}
}
},
{
$project: {
_id: 0,
user: "$_id",
assuntos: {
$filter: {
input: "$assuntos",
as: "assunto",
cond: {
"$and": [
{
$gte: [
"$$assunto.erros",
3
]
},
{
$lte: [
{
$multiply: [
"$$assunto.acertos",
3
]
},
"$$assunto.erros"
]
}
]
}
}
}
}
},
{
"$match": {
assuntos: {
"$exists": true,
"$not": {
"$size": 0
}
}
}
}
])