2011-03-31 19 views
1

我正在嘗試使用Morphia和Play Framework重現一個Post的許多Comment的經典博客模式。MongoDB模式設計 - 查找用戶過濾的所有博客帖子中的最後一條X評論

我在蒙戈架構是:

{ "_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的主頁提供的最後一個X評論那SiteUser的朋友,跨所有職位。

我的型號如下:

@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; 

} 

從我已閱讀elsewhere,我想我需要對數據庫運行下列命令(其中[a, b, c]代表SiteUser S):

db.posts.find({ "comments.commenter" : {$in: [a, b, c]}}) 

我有一個List<SiteUser>傳遞給Morphia的過濾,但我不知道如何

  1. 設立PostComments.commenter索引,從內嗎啡
  2. 實際上建立在Comment類的commenter字段上述查詢

回答

1
  1. 要麼把@Indexes(@Index("comments.commenter"))Post類,或@Indexed( Morphia的Datastore.ensureIndexes()將在類中遞歸,並在Post集合上正確創建comments.commenter索引)

  2. 我認爲ds.find(Post.class, "comments.commenter in", users)會工作,dsDatastoreusers你的List<SiteUser>(雖然我不使用@Reference,所以我不能確認;您可能必須首先提取其Key的列表)。

+0

re你的第二點,是不是會返回Post的實例?我正在尋找關於所有帖子的評論實例。 (對不起,回覆遲了,我已經離開電腦了) – Rich 2011-04-18 11:10:17

+0

是的,它會返回'Post'實例。我不認爲你可以直接得到'Comment'實例,因爲它們是'@ Embedded'對象。 MongoDB無法做到這一點;最終_virtual collections_將使它成爲可能,請參閱http://stackoverflow.com/questions/2138454/filtering-embedded-documents-in-mongodb/2140125#2140125 – 2011-04-19 08:23:29

+0

重點第二點:由於您使用PlayMorphia模塊,一個簡單的方法查詢是'Post post = Post.q()。filter(「comments.commeter in」,users).get()' – 2012-01-17 05:05:50

相關問題