mongo 和 node 中嵌套数组的投影
大家好,我正在尝试通过采用国家代码和州代码来预测属于特定州的城市
[
{
'$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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

我会按如下方式执行此操作:
解释:
仅匹配具有 iso2=IN 和 states.state_code=AG 的文档
(对于此阶段来说,如果您至少在 {iso2:1} 上有索引或在 {iso2:1,states.state_code:1} 上有复合索引,则效果很好)
仅过滤 state_code=AG 的州
$project 仅名称
$unwind 来展平第一个数组。
游乐场
I would do it as follow:
Explained:
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} )
Filter only the states with state_code=AG
$project the names only
$unwind to flatten first array.
playground