mongo 和 node 中嵌套数组的投影

发布于 01-14 04:19 字数 415 浏览 4 评论 0原文

大家好,我正在尝试通过采用国家代码和州代码来预测属于特定州的城市

[
  {
    '$match': {
      'iso2': 'IN'
    }
  }, {
    '$project': {
      'states': {
        '$slice': [
          '$states.cities.name', 1, 1
        ]
      }
    }
  }
]

当我尝试这个时,我得到了结果,但是有没有更好的方法来做到这一点 tq 在此处输入图像描述

hi everyone i am trying to project the cities which are belongs to particular state by taking the country_code and state_code

[
  {
    '$match': {
      'iso2': 'IN'
    }
  }, {
    '$project': {
      'states': {
        '$slice': [
          '$states.cities.name', 1, 1
        ]
      }
    }
  }
]

when i tried this i am getting the result but is there any better way to do it
tq enter image description here

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

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

发布评论

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

评论(1

笔落惊风雨2025-01-21 04:19:17

我会按如下方式执行此操作:

db.collection.aggregate([
{
      "$match": {
      "iso2": "IN",
      "states.state_code": "AG"
}
},
{
  $addFields: {
    states: {
     "$filter": {
       "input": "$states",
       "as": "state",
       "cond": {
         "$eq": [
           "$state.state_code",
           "AG"
        ]
       }
      }
     }
    }
   },
   {
     $project: {
       cities: "$states.cities.name"
   }
   },
  {
    $unwind: "$cities"
  }
])

解释:

  1. 仅匹配具有 iso2=IN 和 states.state_code=AG 的文档
    (对于此阶段来说,如果您至少在 {iso2:1} 上有索引或在 {iso2:1,states.state_code:1} 上有复合索引,则效果很好)

  2. 仅过滤 state_code=AG 的州

  3. $project 仅名称

  4. $unwind 来展平第一个数组。

游乐场

I would do it as follow:

db.collection.aggregate([
{
      "$match": {
      "iso2": "IN",
      "states.state_code": "AG"
}
},
{
  $addFields: {
    states: {
     "$filter": {
       "input": "$states",
       "as": "state",
       "cond": {
         "$eq": [
           "$state.state_code",
           "AG"
        ]
       }
      }
     }
    }
   },
   {
     $project: {
       cities: "$states.cities.name"
   }
   },
  {
    $unwind: "$cities"
  }
])

Explained:

  1. Match only documents having iso2=IN and states.state_code=AG
    ( For this stage is good if you have index on at least {iso2:1} or compound index on {iso2:1,states.state_code:1} )

  2. Filter only the states with state_code=AG

  3. $project the names only

  4. $unwind to flatten first array.

playground

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