我竭尽全力试图在MongoDB中对itens进行分组和计数。有很多帖子,但我不需要。
这是一个基于以下示例: styvane answer
db.VIEW_HISTORICO.aggregate([
{
$match: { PartnerId: "2021", DT_RECEBIDO: {$gte: "2019-03-10 00:00:00", $lte: "2019-03-12 23:59:59"}}
},
{
$group: { _id: null,
Controle1: { $sum: {$cond: [{ $gt: ['$CD_EVENTO', 0]}, 1, 0]}},
Controle2: { $sum: {$cond: [{ $lt: ['$CD_EVENTO', 0]}, 1, 0]}}
}
}
])
我需要根据$ in和$ match进行分组,然后得到一个以上的结果。
一个结果工作
db.VIEW_HISTORICO.aggregate([
{
$match: { PartnerId: "2021", DT_RECEBIDO: {$gte: "2019-03-10 00:00:00", $lte: "2019-03-12 23:59:59"}, "CD_EVENTO": { $in: ["K127", "9027"] }, }
},
{
$count : "Controles"
}
])
使用MSSQL,我可以通过这种方式获得最佳性能:
SELECT
SUM(CASE WHEN CD_EVENTO = 'K102' THEN 1 ELSE 0 END) AS Interfone,
SUM(CASE WHEN CD_EVENTO IN('9015', '9016', '9017', '9018', '9019', '9020', '9021', '9022', '9023', '9024', '9025', '9026', 'K154', 'K155') THEN 1 ELSE 0 END) AS Tag,
SUM(CASE WHEN CD_EVENTO IN('9027', '9028', '9029', '9030', '9031', '9032', '9033', '9034', 'K127') THEN 1 ELSE 0 END) AS Controle,
SUM(CASE WHEN CD_EVENTO IN('K203', 'K204') THEN 1 ELSE 0 END) AS QrCode,
SUM(CASE WHEN CD_EVENTO IN('K183', 'K184') THEN 1 ELSE 0 END) AS Convite
FROM VIEW_ANALYTICS
WHERE DT_RECEBIDO BETWEEN GETDATE()-30 AND GETDATE()
我努力尝试,但无法将MSSQL转换为MongoDB。我的查询。
db.VIEW_HISTORICO.aggregate([
{
$match: { PartnerId: "2021", DT_RECEBIDO: {$gte: "2019-03-10 00:00:00", $lte: "2019-03-12 23:59:59"}}
},
{
$group: { _id: null,
Controle1: { $sum: {$cond: [{ "CD_EVENTO": { $in: ["K127", "9027"] }}, 1, 0]}},
Controle2: { $sum: {$cond: [{ "CD_EVENTO": { $in: ["K154", "K155"] }}, 1, 0]}}
}
}
])
答案 0 :(得分:1)
$in运算符的语法与您在此处尝试执行的操作有点不同。它包含两个元素的数组:第一个元素表示对字段的引用(必须以美元符号开头),第二个元素是值数组,因此您的$group
阶段应如下所示:
db.VIEW_HISTORICO.aggregate([
{
$group: { _id: null,
Controle1: { $sum: {$cond: [{ $in: ["$CD_EVENTO", ["K127", "9027"]]}, 1, 0]}},
Controle2: { $sum: {$cond: [{ $in: ["$CD_EVENTO", ["K154", "K155"]]}, 1, 0]}},
}
}
])