Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

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?

like image 328
Cheok Yan Cheng Avatar asked Feb 24 '17 07:02

Cheok Yan Cheng


1 Answers

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 }
        }
    }
]);
like image 129
chridam Avatar answered Nov 04 '22 02:11

chridam