简体   繁体   English

是否可以在 mongodb 聚合函数中使用“$where”

[英]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.我需要使用聚合函数获取 MongoDB 中字符串值的长度。

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?问题是:是否可以在聚合函数中使用 $where ? or is there any way of getting the length of a string value in aggregation function?或者有没有办法在聚合函数中获取字符串值的长度?

Thanks in advance Eric在此先感谢埃里克

MongoDB doesn't support $where in aggregation pipeline and hope this will never happen, because JavaScript slows things down. MongoDB不支持聚合管道中的$ where ,并希望这种情况永远不会发生,因为JavaScript会降低速度。 Never the less, you still have options: 从来没有,你仍然有选择:

1) Мaintain additional field(eg app_name_len) than will store app_name length and query it, when needed. 1)Мaintain附加字段(例如app_name_len),而不是存储app_name长度并在需要时查询它。

2) You can try extremely slow MapReduce framework, where you allowed to write aggregations with JavaScript. 2)您可以尝试使用极慢的 MapReduce框架,您可以在其中使用JavaScript编写聚合。

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. Mongodb不支持this.app_name.length,但你可以用$ regex来做这个条件 - 这不是很快,但它仍然有效。

{"app_name": { $regex: /^.{12}$/ }}

A simple way to achieve the behaviour expected of OP would be chaining up $expr with $strLenCP实现 OP 预期行为的一种简单方法是将$expr$strLenCP链接起来

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

Mongo Playground蒙戈游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM