问题
I am trying to reproduce the classic blog schema of one Post
to many Comment
s using Morphia and the Play Framework.
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"
}
]}
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.
My models are as follows:
@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;
}
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]}} )
I have a List<SiteUser>
to pass in to Morphia for the filtering, but I don't know how to
- set up an index on
Post
forComments.commenter
from within Morphia - actually build the above query
回答1:
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)I think
ds.find(Post.class, "comments.commenter in", users)
would work,ds
being aDatastore
andusers
yourList<SiteUser>
(I don't use@Reference
though, so I can't confirm; you might have to first extract the list of theirKey
s).
来源:https://stackoverflow.com/questions/5496714/mongodb-schema-design-finding-the-last-x-comments-across-all-blog-posts-filter