过滤 MongoDB 中的嵌入文档 [英] Filtering embedded documents in MongoDB
问题描述
我在掌握如何过滤 MongoDB 中的嵌入文档时遇到问题,开始认为我应该使用关系关联,但在文档存储上下文中感觉不对.
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.
坚持一个典型的博客/评论系统,我有一个博客
的集合,每个blog
都有很多comments
.评论作为嵌入文档存储在博客文档中.
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
,我必须将它们全部加载到内存中(将它们全部检索到一个 Ruby 数组中),并遍历每个评论,返回符合特定条件的评论.
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.
我使用点表示法过滤嵌入文档的努力失败了,并带回了所有子文档.
My efforts to filter embedded documents using dot notation is failing, and bringing back all sub documents.
有没有更好的方法让 MongoDB 为我过滤这些,还是我应该让自己接受关系关联?(拉回所有嵌入的文档并手动过滤从长远来看会过于密集)
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)
推荐答案
目前无法按照您描述的方式过滤嵌入式文档.使用点表示法允许您匹配嵌入的文档,但仍将返回整个文档、父文档和所有文档.也可以选择将返回哪些字段,但这对您的情况也没有真正的帮助.
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
与此同时,您可能应该将评论视为自己的收藏.通常,如果您需要单独使用给定的数据集,请将其设为集合.如果将其作为其他系列的一部分更好地构思,则最好嵌入.
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.
这篇关于过滤 MongoDB 中的嵌入文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!