【问题标题】:MongoDB let variable not working in pipeline aggregationMongoDB让变量在管道聚合中不起作用
【发布时间】:2020-06-08 01:56:21
【问题描述】:

您好,我正在尝试使用我在 let 中定义的变量用于匹配查找,但在使用正则表达式时它不返回任何结果:

它是这样工作的:

db.MSP_Prosper.aggregate([
    { $match: {Cleavage_score: {$gte:0.7}}},
    { $lookup: {
      from:"Uniprot_New_Entries",
      let: { order_item: new RegExp('.*' + "P62258" + '.*')},
      pipeline: [{
        $match: { Uniprot_AC : new RegExp('.*' + "P62258" + '.*')                                      
      }},
      { $project: { _id: 0,
        test: "$$order_item",
        date: { name: "$Uniprot_ID",
        date: "$Min_Max_Of_the_Ft_chain"} 
      }
    }],
       as:"cleavage_sites"
    }   
 }

])

但当我尝试使用 let 函数中定义的相同变量时:

db.MSP_Prosper.aggregate([
    {$match: {Cleavage_score: {$gte:0.7}}},
    {
    $lookup: { from:"Uniprot_New_Entries",
           let: { order_item: new RegExp('.*' + "P62258" + '.*')},
           pipeline: [
             { $match: 
               { Uniprot_AC : "$$order_item" }
             },
             { $project: { _id: 0,
                  test: "$$order_item",
                  date: { name: "$Uniprot_ID",
                          date: "$Min_Max_Of_the_Ft_chain"} 
             }},    
           ],
           as:"cleavage_sites"
    }   
  }
])

最终我想用一个局部变量来复制“P62258” $Protein_ID

希望你能帮忙, 尝试了一切都没有成功。

【问题讨论】:

  • 那么对于MSP_Propsper 集合中得分高于0.7 的每个文档,您要附加来自Uniprot_New_Entries 的每个包含“P62258”的文档吗?如果字符串“P62258”来自原始文档,请通过 let 中的字段名称引用它,并在匹配的 $expr 中构建正则表达式。
  • 嗨,乔,是的,我想附上所有包含 P62258 的文档。这个变量将一直在变化,因为它将是一个来自 MSP_Propsper 集合的变量,变量名为 $Protein。只是为了更容易解释,我对 P62258 进行了硬编码。但不知何故,当由 let 函数定义时,mongoDB 不允许我在匹配正则表达式中使用该变量。
  • new Regexp 在将查询发送到 mongod 节点之前在客户端进行评估,因此它的值不可能根据管道中的文档而改变。
  • 谢谢!这里的答案有所帮助。

标签: database mongodb variables pipeline let


【解决方案1】:

new RegExp 在客户端进行评估并作为绝对值包含在查询中,因此您不能以这种方式包含文档相关变量。

要将文档字段用作查找管道中的正则表达式,您需要使用带有 $regexMatch 聚合运算符的 $expr 子句。请注意,搜索字符串前后的.* 是隐含的,因此是不必要的。

类似:

db.MSP_Prosper.aggregate([
  { $match: { Cleavage_score: { $gte: 0.7 } } },
  { $lookup: {
      from: "Uniprot_New_Entries",
      let: { "order_item": "$Protein_ID" },
      pipeline: [
        {$match: {
            $expr: {
              $regexMatch: {
                input: "$Uniprot_AC",
                regex: "$$order_item"
        }}}},
        {$project: {
            _id: 0,
            test: "$$order_item",
            date: {
              name: "$Uniprot_ID",
              date: "$Min_Max_Of_the_Ft_chain"
        }}},
      ],
      as: "cleavage_sites"
  }}
])

Playground

【讨论】:

  • regex: "$$order_item" 有效,但 regex: "$$order_item.*" 无效。你有这个想法吗?
  • "$$order_item.*" 不明确。它可能表示“字段order_item 后跟任何字符串”,也可能表示“order_item 字段中包含的子文档的字段*”。您可以尝试使用{$concat:["$$order_item",".*"]} 来明确。
猜你喜欢
  • 2018-12-11
  • 1970-01-01
  • 2020-11-01
  • 2020-04-13
  • 2020-08-12
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
相关资源
最近更新 更多