2

The example data is as following:

{"BrandId":"a","Method":"PUT","Url":"/random/widgets/random/state"}
{"BrandId":"a","Method":"POST","Url":"/random/collection/random/state"}
{"BrandId":"b","Method":"PUT","Url":"/random/widgets/random/state"}
{"BrandId":"b","Method":"PUT","Url":"/random/widgets/random/state"}

I need to find all the rows with method=put and Url in a pattern /random/widgets/random/state. "random" is a random string with a fixed length. the expected result is :

{"BrandId":"a","total":1}
{"BrandId":"b","total":2}

I tried to write so code as :

db.accessLog.aggregate([
    {$group: {
        _id: '$BrandId',
        total: {
                $sum:{
                  $cond:[{$and: [ {$eq: ['$Method', 'POST']},
                        {Url:{$regex: /.*\/widgets.*\/state$/}} ]}, 1, 0]
                }
            },
    {$group: {
        _id: '$_id',
       total:{$sum:'$total'}
    }
])

but the regular expression does not work, so I suppose I need to try other way to do it, perhaps split string. And I need to use $cond. please keep it. Thanks!

erkpwejropi
  • 391
  • 1
  • 7
  • 18

2 Answers2

1

You can use the following query to achieve what you want, I assume the data in a collection named 'products'

db.products.aggregate([
                {$match : {'Method':'PUT','Url':/.*widgets.*\/state$/ }},
                {$group: {'_id':'$BrandId','total':{$sum: 1} }}
        ]);

1. $match: Find all documents that has 'PUT' method and Url in the specified pattern.

2. $group: Group by brand Id and for each entry, count 1

Toan Nguyen
  • 11,263
  • 5
  • 43
  • 59
0

Greedy matching is the problem.

Assuming non-zero number of 'random' characters (sounds sensible), try a regex of:

/[^\/]+\/widgets\/[^\/]+\/state$/
Community
  • 1
  • 1
declension
  • 4,110
  • 22
  • 25
  • Sorry, I suppose regular expression does not work in $cond. as I mentioned that I need another way to do it. – erkpwejropi May 13 '15 at 23:36
  • Looks like [you can't do that](http://docs.mongodb.org/manual/reference/operator/aggregation/group/#accumulator-operator). Perhaps you should just filter your collection before aggregating, i.e. use a `$match` with `$regex` ([which *is* supported](http://docs.mongodb.org/manual/reference/operator/query/#query-selectors)). – declension May 14 '15 at 08:42