MongoDB模式设计-在按用户筛选的所有博客文章中查找最后X条评论 [英] MongoDB schema design - finding the last X comments across all blog posts filtered by user
问题描述
我正在尝试使用Morphia和Play Framework将一个Post
的经典博客架构重现为许多Comment
.
I am trying to reproduce the classic blog schema of one Post
to many Comment
s using Morphia and the Play Framework.
我在Mongo中的架构是:
My schema in Mongo is:
{ "_id" : ObjectId("4d941c960c68c4e20d6a9abf"),
"className" : "models.Post",
"title" : "An amazing blog post",
"comments" : [
{
"commentDate" : NumberLong("1301552278491"),
"commenter" : {
"$ref" : "SiteUser",
"$id" : ObjectId("4d941c960c68c4e20c6a9abf")
},
"comment" : "What a blog post!"
},
{
"commentDate" : NumberLong("1301552278492"),
"commenter" : {
"$ref" : "SiteUser",
"$id" : ObjectId("4d941c960c68c4e20c6a9abf")
},
"comment" : "This is another comment"
}
]}
我正在尝试向博客介绍社交网络方面,因此我希望能够在SiteUser
的主页上提供所有帖子中该SiteUser
的朋友的最后X条评论.
I am trying to introduce a social networking aspect to the blog, so I would like to be able to provide on a SiteUser
's homepage the last X comments by that SiteUser
's friends, across all posts.
我的模型如下:
@Entity
public class Post extends Model {
public String title;
@Embedded
public List<Comment> comments;
}
@Embedded
public class Comment extends Model {
public long commentDate;
public String comment;
@Reference
public SiteUser commenter;
}
根据我已阅读的内容在其他地方,我认为我需要对数据库(其中[a, b, c]
代表SiteUser
s)运行以下命令:
From what I have read elsewhere, I think I need to run the following against the database (where [a, b, c]
represents the SiteUser
s) :
db.posts.find( { "comments.commenter" : {$in: [a, b, c]}} )
我有一个List<SiteUser>
可以传递给Morphia进行过滤,但是我不知道如何
I have a List<SiteUser>
to pass in to Morphia for the filtering, but I don't know how to
- 在Morphia中为
Comments.commenter
在Post
上设置索引 - 实际构建以上查询
- set up an index on
Post
forComments.commenter
from within Morphia - actually build the above query
推荐答案
-
将
@Indexes(@Index("comments.commenter"))
放在Post
类上,或者将@Indexed
放在Comment
类的commenter
字段上(Morphia的Datastore.ensureIndexes()
将在这些类中递归并正确创建Post
集合上的索引)
Either put
@Indexes(@Index("comments.commenter"))
on thePost
class, or@Indexed
on thecommenter
field of theComment
class (Morphia'sDatastore.ensureIndexes()
will recurse in the classes and correctly create thecomments.commenter
index on thePost
collection)
我认为ds.find(Post.class, "comments.commenter in", users)
可以工作,ds
是Datastore
,而users
是您的List<SiteUser>
(尽管我不使用@Reference
,所以我无法确认;您可能会必须首先提取其Key
的列表.)
I think ds.find(Post.class, "comments.commenter in", users)
would work, ds
being a Datastore
and users
your List<SiteUser>
(I don't use @Reference
though, so I can't confirm; you might have to first extract the list of their Key
s).
这篇关于MongoDB模式设计-在按用户筛选的所有博客文章中查找最后X条评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!