c# - 使用聚合从 mongodb 中的 order by 和 group by 联合选择

标签 c# mongodb aggregation-framework mongodb-.net-driver

我尝试使用 C# 聚合框架将下一个 SQL 查询重写到 mongodb,但我不明白该怎么做。我需要合并一些结果。

SELECT TOP 100 RES.Agent, RES.Type, RES.Opens FROM ((SELECT UA.ClientDomain AS Agent, UA.Type AS Type, COUNT(*) AS Opens 
                                                    FROM tReadConfirm AS RC INNER JOIN tUserAgent AS UA ON RC.UserAgentId = UA.Id
                                                    WHERE RC.UserId = 2654 AND RC.CampaignId = 27442  AND UA.Type = 1
                                                    GROUP BY UA.ClientDomain, UA.Type)
                                                UNION
                                                (SELECT UA.Family AS Agent, UA.Type AS Type, COUNT(*) AS Opens 
                                                    FROM tReadConfirm AS RC INNER JOIN tUserAgent AS UA ON RC.UserAgentId = UA.Id
                                                    WHERE RC.UserId = 2654 AND RC.CampaignId = 27442 AND UA.Type <> 1
                                                    GROUP BY UA.Family, UA.Type)) AS RES
                                                ORDER BY RES.Opens DESC

这是我的开始代码,但它不能满足我的需要

db.analytics.aggregate(
    {
        $match: { UserId: 4749, CampaignId: 93178}
    },
    {
        $group :
        {
            _id : 
            { 
                "Family" : "$userAgent.Family",
                "Type" : "$userAgent.Type",
                "ClientDomain" : "$userAgent.ClientDomain",
            }  ,
            "Opens": 
            {
                 $sum : 1 
            }
         }
     },
     {$sort :{"Opens":-1}}
)

最佳答案

我找到了答案,这是我的工作代码示例。运算符“$cond”帮助了我。

db.analytics.aggregate(

    { 
        $match : { 
            "UserId" : 4790, 
            "CampaignId" : 93178} 
     },
     {
        $group :
        {
            _id : 
            { 
                "Type" : "$userAgent.Type",
                "ClientDomain" : { $cond: { if: { $eq: [ "$userAgent.Type", 1 ] }, then: "$userAgent.ClientDomain", else: "$userAgent.Family" }},
            }  ,
            "Opens": 
            {
                 $sum : 1 
            }
         }
     },
     {
         $sort :{"Opens":-1}
     },
     {
         $limit:10
     }
)

关于c# - 使用聚合从 mongodb 中的 order by 和 group by 联合选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31568206/

相关文章:

c# - 通过 Resharper 或 DevExpress 的方法进行依赖注入(inject)

c# - 如何重构此 ForEach(..) 代码以使用 Parallel.ForEach(..)?

c# - this.Type 保留?应报

mongodb - 在Go中删除MongoDB中的数组元素

php - 卸载mongodb php驱动并安装不同的版本

mongodb - 填充 $lookup 中的特定字段

java - 具有多个条件的聚合

c# - MS 图表 : How can you change the color of each label on the Axis of a Bar Chart?

mongodb - 无法在 Ubuntu 12.04 上启动 mongodb-linux-2.4.1

node.js - 当嵌套数组为空时,$lookup 和 $unwind 不会给出结果