如何使用MongoDB中的数组嵌套过滤器获取特定的字段值?
在滤波嵌套数组值之后,我添加了“ $ project”查询以选择特定字段。
我想在嵌套数组之外获得“ new_yn”字段值,但我只有ID和嵌套数组值。
我该如何修复查询?你会给我一些指南吗? (MongoDB版本是5.0.6社区)
[QUERY]
db.collection.aggregate([
{
$match: {
"new_yn": "Y",
"port_info": {
$elemMatch: {
"port_code": "http_https"
}
}
}
},
{
$project: {
port_info: {
$filter: {
input: "$port_info",
as: "item",
cond: {
$eq: [
"$$item.port_code",
"http_https"
]
}
}
}
}
},
{
"$project": {
"_id": 1,
"new_yn": 1,
"port_info.ip_port": 1
}
}
])
[Mongo Playground]
After I filtered nested array values then I added "$project" query for selecting specific fields.
I want to get "new_yn" field values outside of the nested array but I only got id and nested array values.
How can I fix my Query? Would you give me some guides?
(MongoDB version is 5.0.6 Community)
[Query]
db.collection.aggregate([
{
$match: {
"new_yn": "Y",
"port_info": {
$elemMatch: {
"port_code": "http_https"
}
}
}
},
{
$project: {
port_info: {
$filter: {
input: "$port_info",
as: "item",
cond: {
$eq: [
"$item.port_code",
"http_https"
]
}
}
}
}
},
{
"$project": {
"_id": 1,
"new_yn": 1,
"port_info.ip_port": 1
}
}
])
[Mongo Playground]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为您还没有将其包括在第一个
$ project
阶段。只需将
new_yn:1
添加到第一个项目阶段,它将起作用。如建议由伯利恒,您可以使用
$ set
也将带来该文档中的所有其他字段,我相信您不想要。This is because you haven't included it in the first
$project
stage.Just add
new_yn:1
to the first project stage and it will work.As suggested by Bethlee, you can use
$set
as well, but it will bring all other fields from that document, which I believe you dont want.