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?
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 }
}
}
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With