如何在项目蒙戈外壳查询嵌套数组的唯一匹配字段 [英] How to project only matching fields of nested array in mongo shell query
问题描述
我是相当新的MongoDB的,我也希望如此一个简单的问题:
I am fairly new to mongodb, and I have what is hopefully a simple question:
我有一个嵌套的模式,我有一个字段是一个数组,数组的每一个项目是一个对象,它本身有一个数组字段。
I have a nested schema where I have a field that is an array, where each item of that array is an object that itself has an array field.
例如:
> db.mytest.insert({
name: 'a',
top: [
{x:1, y:2, nest: [{p:1, q:2}, {p:2, q:3}]},
{x:2, y:3, nest: [{p:4, q:5}, {p:6, q:7}]}
]
})
我可以查询的p就好了一定的值,甚至可以我的结果限制在顶
的第一个匹配的元素:
> db.mytest.findOne({'top.nest': {$elemMatch: {p:6}}}, {'top.nest.$': 1})
{"_id":ObjectId(...), top: [{x:2, y: 3, nest: [{p:4, q:5}, {p:6, q:7}]}]}
这让我想起我的问题: {'top.nest $':1}
和 {'顶$':1}
我的投影文件都返回相同的结果。如何限制我的搜索结果仅包括巢
的一个匹配的元素?
Which brings me to my question: {'top.nest.$': 1}
and {'top.$': 1}
as my projection document both return the same result. How can I limit my search results to only include the first matching element of nest
?
我是否需要第二次,超过这种风格的查询结果迭代?
Do I need a second pass that iterates over the result of this style of query?
推荐答案
好吧,诀窍是的聚合框架,特别是放松。
> db.mytest.aggregate({$unwind: '$top'},
{$unwind: '$top.nest'},
{$match: {'top.nest.p': 6}}
)
虽然在我在一个单一的对象具有多个子场的情况下,这将返回而不是在其原始分组形式多个结果。我想我可以把一个 $组
进入管道,虽然。
虽然我找到了相关链接建议重新设计架构作为唯一的完整的修补程序,现在,所以这绝对是聊胜于无。
Though the related links I found suggested schema redesign as the only complete fix right now, so this is definitely better than nothing.
这篇关于如何在项目蒙戈外壳查询嵌套数组的唯一匹配字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!