如何在数组元素中使用mongoDB投影查询
我只想在菜单中投射“类型”:“ a”。有没有办法实现这一目标?
"_id" : "1",
"menu" : [
{
"type" : "A",
"items" : [
{
"key" : "Add",
"enabled" : true,
} ]
},
{
"type" : "B",
"items" : [
{
"key" : "Add",
"enabled" : true,
} ]
}
]
}
I would like to project only "type":"A" in menu. is there a way to achieve this?
"_id" : "1",
"menu" : [
{
"type" : "A",
"items" : [
{
"key" : "Add",
"enabled" : true,
} ]
},
{
"type" : "B",
"items" : [
{
"key" : "Add",
"enabled" : true,
} ]
}
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果只需tou输出菜单,哪个类型为a,则可以在查找查询中使用
$ elemmatch
(请注意,因为此仅返回第一个匹配的元素)示例
在这里或
$ filter
(这将带有type
类型:代码>在数组中):
示例在这里
If you want tou output only the menu which type is A you can use
$elemMatch
in a find query (take care because this only return the first matched element)Example here
Or
$filter
in an aggregate query (this returns all objects withtype: "A"
in the array):Example here