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

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

 

Filed 2018-05-23 09:55:55 by Anonymous (not verified)

  • Log in  to comment
  • 102 views

Article content can be translated into Chinese, ad blocking plug-ins may cause the functional failure (such as failure, please turn off ad blocking plug-ins and try again):

Select a language Chinese (Simplified) Japanese English Chinese (Traditional)

By the  Google Translatetranslator Powered

problem:

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?

Answer 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 }
        }
    }
]);

 

Guess you like

Origin blog.csdn.net/cxu123321/article/details/92003289