【问题标题】:Using cond to specify _id fields for group in mongodb aggregation使用 cond 为 mongodb 聚合中的组指定 _id 字段
【发布时间】:2021-10-18 22:11:06
【问题描述】:

Mongo 新手。尝试根据条件对文档的不同子字段进行分组。条件是字段值的正则表达式。好像——

db.collection.aggregate([{
        {
            "$group": {
                "$cond": [{
                        "upper.leaf": {
                            $not: {
                                $regex: /flower/
                            }
                        }
                    },

                    {

                        "_id": {
                            "leaf": "$upper.leaf",
                            "stem": "$upper.stem"
                        }

                    },
                    {

                        "_id": {
                            "stem": "$upper.stem",
                            "petal": "$upper.petal"
                        }

                    }
                ]
            }
        }])

使用 api v4.0:文档中的 cond 显示 - { $cond: [ <boolean-expression>, <true-case>, <false-case> ] }

我用上面的代码得到的错误是-"Syntax error: dotted field name 'upper.leaf' can not used in a sub object."

阅读后,我尝试使用 $let 重新分配虚线字段名称。但开始遇到各种语法错误,查询中没有明显问题。

还尝试使用 $project 重命名字段,但得到 - Field names may not start with '$'

认为这里的最佳方法是什么?我总是可以在应用程序级别解决这个问题并将我的查询分成两部分,但在 mongo 中本地解决它可能很有吸引力。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    $group 语法错误

    {
      $group:
        {
          _id: <expression>, // Group By Expression
          <field1>: { <accumulator1> : <expression1> },
          ...
        }
     }
    

    你试图这样做

    {
      $group:
        <expression>   
     }
    

    即使您的表达式产生相同的代码,$group 的语法也是无效的(查看允许使用表达式的文档)

    另一个问题是您对正则表达式使用查询运算符,而不是聚合正则表达式运算符(您不能这样做,如果您聚合,则只能使用聚合运算符,只有 $match 是您可以使用的例外如果您添加$expr,请同时使用)

    我认为你需要这个

    [{
      "$group" : {
        "_id" : {
          "$cond" : [ {
            "$not" : [ {
              "$regexMatch" : {
                "input" : "$upper.leaf",
                "regex" : "/flower/"}}]}, 
           {"leaf" : "$upper.leaf","stem" : "$upper.stem"},
           {"stem" : "$upper.stem","petal" : "$upper.petal"}]
          }
      }}]
    

    其代码类似,但表达式获取为“_id”和$regexMatch 的值 使用的是聚合运算符。

    我没有测试代码。

    【讨论】:

      猜你喜欢
      • 2016-08-16
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      相关资源
      最近更新 更多