8

I need to get the length of a string value in MongoDB using aggregation functions.

it works in

db.collection_name.find({"$where":"this.app_name.length===12"})

but when implanted to

db.collection_name.aggregate({$match: 
                                 {"$where":"this.app_name.length===12"}
                                 },
                             {
                             $group :
                                  {
                                  _id : 1,
                                   app_downloads : {$sum: "$app_downloads"}
                                  }
                             }

);

I got this result:

failed: exception: $where is not allowed inside of a $match aggregation expression

The question is: is it possible to use $where in aggregation functions? or is there any way of getting the length of a string value in aggregation function?

Thanks in advance Eric

EricSRK
  • 145
  • 3
  • 8
  • possible duplicate of [Select string length in mongodb](http://stackoverflow.com/questions/14647644/select-string-length-in-mongodb) – WiredPrairie Jun 24 '13 at 18:18

3 Answers3

5

MongoDB doesn't support $where in aggregation pipeline and hope this will never happen, because JavaScript slows things down. Never the less, you still have options:

1) Мaintain additional field(e.g. app_name_len) than will store app_name length and query it, when needed.

2) You can try extremely slow MapReduce framework, where you allowed to write aggregations with JavaScript.

Artem Mezhenin
  • 5,539
  • 6
  • 32
  • 51
0

Today I had the same problem.

Mongodb doesn't support this.app_name.length, but you can do this condition with $regex - this is not very quick, but it still works.

{"app_name": { $regex: /^.{12}$/ }}
yAnTar
  • 4,269
  • 9
  • 47
  • 73
0

A simple way to achieve the behaviour expected of OP would be chaining up $expr with $strLenCP

db.collection.find({
  $expr: {
    $eq: [
      12,
      {
        $strLenCP: "$app_name"
      }
    ]
  }
})

Mongo Playground

ray
  • 11,310
  • 7
  • 18
  • 42