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

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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}$/ }}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.