从使用聚合的mongodb中的order by和group by中选择union选择

时间:2015-07-22 15:57:10

标签: 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}}
)

2 个答案:

答案 0 :(得分:4)

我找到了答案,这是我的工作代码示例。运营商&#34; $ cond&#34;帮助我。

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
     }
)

答案 1 :(得分:0)

您可以尝试以下想法:

  1. 过滤常用部分 - 您已在$ match stage
  2. 中完成此操作
  3. 通过$ project运算符获取新的文档结构。像

    这样的东西

    {剂: [{Agent:“$ userAgent.Family”,Index:0},{Agent:“$ userAgent.ClientDomain”,Index:1}],类型:“$ userAgent.Type”}

  4. $展开代理字段,这样您就可以获得2个文档而不是1个包含2个元素数组的文档。

  5. 使用以下想法重新过滤:{$或:[{Index:0,Type:1},{Index:1,Type&lt;&gt; 1}]}

  6. 按代理,类型和索引字段分组。

  7. 如果我没弄错的话,你会得到同样的结果。

    编辑:不幸的是,第2步无效。 MongoDB: how create a new array field with the aggregate framework