You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合中如何在表达式后直接访问嵌套元素?

可行,无需额外$project阶段

直接在当前的第三个$project阶段里修改binding的表达式,就能让它直接返回35,不用加额外阶段。

修改后的聚合管道:

[
  {"$project":
    {
      "refAgentId":true,"_id":false
    }
  },
  {
    "$lookup":
    {
      "from":"policyTransactions",
      "let":{"refAgentId":"$refAgentId"},
      "pipeline":[],
      "as":"bind"
    }
  },
  {
    "$project":{
      "refAgentId":true,
      "binding":{
        "$getField": {
          "field": "bind",
          "input": {
            "$arrayElemAt":[{
              "$filter":{
                "input":"$bind",
                "as":"a",
                "cond":{
                  "$eq":[
                    "$refAgentId",
                    "$$a.refAgentId"]}}},
            0]
          }
        }
      }
    }
  }
]

说明:

这里用$getField操作符,直接从$arrayElemAt返回的对象中提取bind字段的值。如果你的MongoDB版本是5.0及以上,也可以用更简洁的写法——把$arrayElemAt的结果作为对象,直接通过点语法访问,但$getField兼容性更好(支持MongoDB 4.4+)。

修改后返回结果:

{
  "refAgentId": "d6ae049b-edb6-4e55-b3d3-ae994d02fd02",
  "binding": 35
}

内容的提问来源于stack exchange,提问作者user12685852

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:20:27