regex - How to split string in MongoDB? -
the example data 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 find rows method=put , url in pattern /random/widgets/random/state. "random" random string fixed length. expected result :
{"brandid":"a","total":1} {"brandid":"b","total":2}
i tried write code :
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 regular expression not work, suppose need try other way it, perhaps split string. , need use $cond. please keep it. thanks!
greedy matching problem.
assuming non-zero number of 'random' characters (sounds sensible), try regex of:
/[^\/]+\/widgets\/[^\/]+\/state$/
Comments
Post a Comment