Search code examples
mongodbpymongo

is it possible to use "$where" in mongodb aggregation functions


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


Solution

  • 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.