FieldPath field names may not contain '.' in $group

FieldPath field names may not contain '.' in $group

 

由 匿名 (未验证) 提交于 2018-05-23 09:55:55

  • 登录 发表评论
  • 102 次浏览

可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):

选择语言中文(简体)日语英语中文(繁体)

由 Google 翻译翻译强力驱动

问题:

I have the following mongo data which looks like this

{
    eventType : "mousedown",
    eventArgs : {
        type : "touchstart",
        elementId : "id1"
    },
    creationDateTime : ISODate("2017-02-24T07:05:49.986Z")
}

I wrote the following query to perform group count.

db.analytics.aggregate
(
    {
        $match :
        {
            $and : 
            [
                {"eventArgs.type" : 'touchstart'}, 
                {eventType : 'mousedown'}, 
                {creationDateTime : {$gte : ISODate("2017-02-24T000:00:00.000Z")}}
            ]
        }
    },
    {
        $group : 
        {
            _id : 
            {
                "eventsArgs.elementId" : "$elementId"
            },
            count : 
            {
                $sum : 1
            }
        }
    }
);

I'm getting error for $group, which states that

FieldPath field names may not contain '.'

If I were not able to specific '.' in

        $group : 
        {
            _id : 
            {
                "eventsArgs.elementId" : "$elementId"
            },

What is the correct way to do so?

回答1:

Since you have a single group field, the best way is to just use the _id group key on that field and then create another $project pipeline that will reshape the _id key from the previous pipeline into the desired subdocument that you want. For example

db.analytics.aggregate([
    {
        "$match": {
            "eventArgs.type": 'touchstart', 
            "eventType": 'mousedown', 
            "creationDateTime": { "$gte": ISODate("2017-02-24T000:00:00.000Z") } 
        }
    },
    {
        "$group": {
            "_id": "$eventArgs.elementId",
            "count": { "$sum": 1 }
        }
    },
    {
        "$project": {
            "eventsArgs.elementId": "$_id",
            "count": 1, "_id": 0
        }
    }
]);

The following should work as well:

db.analytics.aggregate([
    {
        "$match": {
            "eventArgs.type": 'touchstart', 
            "eventType": 'mousedown', 
            "creationDateTime": { "$gte": ISODate("2017-02-24T000:00:00.000Z") } 
        }
    },
    {
        "$group": {
            "_id": {
               "eventArgs": {
                   "elementId": "$eventArgs.elementId"
               }
            },
            "count": { "$sum": 1 }
        }
    }
]);

 

posted @ 2019-06-14 20:12  grj001  阅读(107)  评论(0编辑  收藏  举报