从数组 mongodb 中的特定对象元素投影一个字段

发布于 2025-01-16 18:40:11 字数 547 浏览 0 评论 0原文

我有一个集合:

{
    "_id": 1,
    "_deleted": false,
    "customFields": [{
        "fieldName": "sapID",
        "value": ""
    }, {
        "fieldName": "salesTerritory",
        "value": ""
    }, {
        "fieldName": "clientType",
        "value": "Corporate"
    }],
}

如何project(aggregate)仅使用fieldName =“clientType”元素的value字段:

db.collection.aggregate(
    {
        $project:{value:<code>}
    }
)

我尝试了< code>$filter 但它不起作用

I have a collection:

{
    "_id": 1,
    "_deleted": false,
    "customFields": [{
        "fieldName": "sapID",
        "value": ""
    }, {
        "fieldName": "salesTerritory",
        "value": ""
    }, {
        "fieldName": "clientType",
        "value": "Corporate"
    }],
}

How can I project(aggregate) only the value field of the element with fieldName = "clientType":

db.collection.aggregate(
    {
        $project:{value:<code>}
    }
)

I tried $filter but it does not work

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷夜 2025-01-23 18:40:11
db.collection.aggregate([
  {
    $project: {
      "customFields.value": 1
    }
  }
])

mongoplayground


db.collection.aggregate([
  {
    $set: {
      customFields: {
        $map: {
          input: "$customFields",
          as: "c",
          in: {
            $cond: {
              if: { "$eq": [ "$c.fieldName", "clientType" ] },
              then: { value: "$c.value" },
              else: "$c"
            }
          }
        }
      }
    }
  }
])

mongoplayground

db.collection.aggregate([
  {
    $project: {
      "customFields.value": 1
    }
  }
])

mongoplayground


db.collection.aggregate([
  {
    $set: {
      customFields: {
        $map: {
          input: "$customFields",
          as: "c",
          in: {
            $cond: {
              if: { "$eq": [ "$c.fieldName", "clientType" ] },
              then: { value: "$c.value" },
              else: "$c"
            }
          }
        }
      }
    }
  }
])

mongoplayground

岁吢 2025-01-23 18:40:11

这又如何呢?

db.collection.aggregate([
   {
      $project: {
         customFields: {
            $filter: {
               input: "$customFields",
               $cond: { $eq: ["$this.fieldName", "clientType"] }
            }
         }
      }
   }
])

Mongo 游乐场

What about this?

db.collection.aggregate([
   {
      $project: {
         customFields: {
            $filter: {
               input: "$customFields",
               $cond: { $eq: ["$this.fieldName", "clientType"] }
            }
         }
      }
   }
])

Mongo Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文