MongoDB - 通过子树查询
我的文档结构与下面所示的简化版本相同:
{
some_other_props: { ... },
systems: {
sys1: {
score: 24,
metric: 52
},
another_sys: {
score: 9,
metric: 77
},
some_other_sys: {
score: 12,
metric: 5
}
}
}
我想返回所有子文档,其中 score : { "$gte" : 15 }
为 true文件。
我能想到的唯一方法是获取系统中的键列表并将其连接成某种或语句的混乱。但似乎我做错了什么。
我可以重新格式化文档结构,以便每个系统都在自己的文档中...但是 some_other_props
中有很多其他信息,现在重新格式化会很痛苦。
事实上,我正在尝试做一些更复杂的事情。返回同一系统的score
和metric
差异很大的所有文档。但在我这样做之前,我想确保我可以对子树进行简单的查询,如上面所示。
谁能建议如何查询 MongoDB 中的子树?
I have a document structure that the same as the simplified version shown below:
{
some_other_props: { ... },
systems: {
sys1: {
score: 24,
metric: 52
},
another_sys: {
score: 9,
metric: 77
},
some_other_sys: {
score: 12,
metric: 5
}
}
}
I'd like to return all the documents where score : { "$gte" : 15 }
is true for any of the sub-documents.
The only way I could think of doing this was to get the list of keys in system
and concat that into some kind of or-statement mess. But it seems like I'm doing something wrong.
I could reformat the document structure so that each system is in its own document... but there's a lot of other information in some_other_props
and reformatting now would be a pain.
In truth I'm trying to do something a bit more complex. Return all the documents where the difference between the score
and metric
of the same system are very different. But before I can do that I wanted to make sure I could just do simple queries on sub-trees as I've shown above.
Can anyone suggest how to query sub-trees in MongoDB?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该考虑将子文档存储为数组:
然后您可以只查询
find 'systems.score' : { '$gte' : 15 }
,还可以为 'systems 建立索引.score'(如果您觉得需要的话)。You should consider storing the sub-documents as an array:
Then you can just query
find 'systems.score' : { '$gte' : 15 }
, and you can also build an index for 'systems.score' if you feel that you need it.如果您现在确切地得到了分数,您可以进行一个胖“或”查询:
但这似乎是解决问题的蹩脚方法。所以我的建议是为
system_scores
创建一个不同的目录,其中对system_props
集合有多对一的引用。这将使查询变得更加容易。If you now exactly what is getting scored you can make a fat "or" query :
but it seems like a lame way to solve the problem. so my suggestion is make a different catalog for
system_scores
which have a many to one reference tosystem_props
collection. That would make it much more easier to query.