MongoDB schema design - finding the last X comments across all blog posts filtered by user

邮差的信 提交于 2019-12-23 02:19:23

问题


I am trying to reproduce the classic blog schema of one Post to many Comments 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 SiteUsers) :

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

  1. set up an index on Post for Comments.commenter from within Morphia
  2. actually build the above query

回答1:


  1. Either put @Indexes(@Index("comments.commenter")) on the Post class, or @Indexed on the commenter field of the Comment class (Morphia's Datastore.ensureIndexes() will recurse in the classes and correctly create the comments.commenter index on the Post collection)

  2. 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 Keys).



来源:https://stackoverflow.com/questions/5496714/mongodb-schema-design-finding-the-last-x-comments-across-all-blog-posts-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!