【问题标题】:Temporary Tables (CTE) in MongoDBMongoDB 中的临时表 (CTE)
【发布时间】:2022-01-09 05:34:46
【问题描述】:

我知道公用表表达式 (CTE) 又名“临时命名结果集”可以在 SQL 中用于生成临时表,但是这可以在 MongoDB 中完成吗?我想要一个文档,但它只是在我的查询中临时使用。

能否在不创建新集合的情况下在 MongoDB 中创建临时表?

例如,如果我要尝试在 Mongo 中重新创建以下代码...

SQL 中的 CTE 表示例:

n f1 f2
1 20 12
2 40 0.632
3 60 0.647
WITH RECURSIVE example (n, f1, f2) AS 
( SELECT 1, 20, 12
UNION ALL  SELECT 
n + 1,
n * 20, 
least(6*n, $globalVar * 100),
FROM example WHERE n < 3
) SELECT * FROM example

【问题讨论】:

  • 我知道$graphLookup 阶段,但我认为这不适合我的用例...我不需要传递集合
  • 最好发布在姐妹网站DBA.StackExchange.com

标签: mysql sql mongodb mongodb-query aggregation-framework


【解决方案1】:

在 MongoDB 中似乎没有 CTE 的通用等价物。但是,对于 OP 的示例,可以对 $range 的输出进行争吵以产生类似的效果。

// whichever collection doesn't matter; as long as it has 1 document then it should be fine
db.collection.aggregate([
  {
    // jsut take 1 document
    "$limit": 1
  },
  {
    // use $range to generate iterator [1, 2, 3]
    "$addFields": {
      "rg": {
        "$range": [
          1,
          4
        ]
      },
      globalVar: 0.001
    }
  },
  {
    // do the mapping according to logic
    "$addFields": {
      "cte": {
        "$map": {
          "input": "$rg",
          "as": "n",
          "in": {
            n: "$$n",
            f1: {
              "$multiply": [
                "$$n",
                20
              ]
            },
            f2: {
              "$cond": {
                "if": {
                  $lt: [
                    {
                      "$multiply": [
                        "$$n",
                        6
                      ]
                    },
                    {
                      "$multiply": [
                        "$globalVar",
                        100
                      ]
                    }
                  ]
                },
                "then": {
                  "$multiply": [
                    "$$n",
                    6
                  ]
                },
                "else": {
                  "$multiply": [
                    "$globalVar",
                    100
                  ]
                }
              }
            }
          }
        }
      }
    }
  },
  {
    // wrangle back to expected form
    "$unwind": "$cte"
  },
  {
    "$replaceRoot": {
      "newRoot": "$cte"
    }
  }
])

这里是Mongo playground 供您参考。

【讨论】:

  • $$n中$$的意义是什么?在@ray 之前,我从未在 Mongo 中遇到过双美元符号
  • @cramos24 $$ 通常用于引用变量。在我们的例子中,n 被“声明”为$map 的变量。您可以查看this official document 了解更多信息
猜你喜欢
  • 2014-06-03
  • 2015-11-09
  • 2022-10-05
  • 2017-05-27
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-15
相关资源
最近更新 更多