过滤 MongoDB 中的嵌入文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2138454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filtering embedded documents in MongoDB
提问by kez
I am having trouble grasping how to filter embedded documents in MongoDB, and am starting to think I should be using a relational association, but that feels wrong in the document-store context.
我在掌握如何过滤 MongoDB 中的嵌入式文档时遇到了麻烦,并且开始认为我应该使用关系关联,但这在文档存储上下文中感觉是错误的。
Sticking with a typical blog/comment system, I have a collection of blogs
, and each blog
has many comments
. The comments are stored as embedded documents inside the blog document.
坚持一个典型的博客/评论系统,我有一个集合blogs
,每个blog
都有很多comments
. 评论作为嵌入文档存储在博客文档中。
It is very simple to filter my blogs
collection, but in order to filter my comments
embedded in each blog
, I am having to load them all into memory (retrieve all into a Ruby array), and loop through each comment, returning ones that match a specific criteria.
过滤我的blogs
集合非常简单,但是为了过滤我comments
嵌入的每个blog
,我必须将它们全部加载到内存中(检索所有到 Ruby 数组中),并遍历每个评论,返回匹配特定条件的评论.
My efforts to filter embedded documents using dot notation is failing, and bringing back all sub documents.
我使用点符号过滤嵌入文档的努力失败了,并带回了所有子文档。
Is there a better way of getting MongoDB to filter these for me, or should I resign myself to relational associations? (Pulling back all embedded documents and manually filtering is going to be too intensive in the long run)
有没有更好的方法让 MongoDB 为我过滤这些,或者我应该让自己接受关系关联?(从长远来看,拉回所有嵌入的文档并手动过滤将过于密集)
采纳答案by Kyle Banker
There's currently no way to filter on embedded docs in the way you're describing. Using the dot notation allows you to match on an embedded doc, but the entire document, parent and all, will still be returned. It's also possible to select which fields will be returned, but that doesn't really help your case, either.
目前无法按照您描述的方式过滤嵌入式文档。使用点表示法允许您匹配嵌入的文档,但仍将返回整个文档、父文档和所有文档。也可以选择将返回哪些字段,但这对您的情况也没有真正的帮助。
We have a "virtual collections" case, which would implement the desired functionality; feel free to vote on it:
我们有一个“虚拟集合”案例,它将实现所需的功能;随意投票:
http://jira.mongodb.org/browse/SERVER-142
http://jira.mongodb.org/browse/SERVER-142
In the meantime, you should probably treat comments as their own collection. In general, if you need to work with a given data set on its own, make it a collection. If it's better conceived of as part of some other set, it's better to embed.
同时,您可能应该将评论视为自己的收藏。通常,如果您需要单独使用给定的数据集,请将其设为集合。如果更好地将其作为其他集合的一部分进行构思,则最好嵌入。