简体   繁体   English

基于深度嵌套对象单个字段的morphia查询

[英]morphia query based on single field of deeply nested object

I want to retrieve an object, based on an id (or other single field) of an object that is nested 2 levels from the object that I want to retrieve. 我想根据对象的id(或其他单个字段)检索一个对象,该对象嵌套在我想要检索的对象的2个级别。 An example to demonstrate: 举例说明:

I want to find all blog posts that have been commented on by a particular user. 我想查找特定用户评论过的所有博客帖子。

Blog
  List<Comment>
    ignoredField1
    ignoredField2
    User
      id
      name
      ignoredField3

Comments and Users are @Referenced by their parent objects. 注释和用户由其父对象@Referenced。

After reading this post http://groups.google.com/group/morphia/browse_thread/thread/57090ef1bd2f3e74?pli=1 阅读此帖后http://groups.google.com/group/morphia/browse_thread/thread/57090ef1bd2f3e74?pli=1

I understand how i would find blogs with comments where ignoredField1/2 has a particular value, but i want to navigate further than that. 我理解如何找到带有注释的博客,其中ignoredField1 / 2具有特定值,但我想要进一步导航。

I have tried the following but because all Comment fields are compared, there is no match 我尝试了以下但是因为比较了所有的Comment字段,所以没有匹配

q.field("comments").hasThisElement(new Comment(new User("name")));

You'll have to do it in a fews of steps I think: 你必须在几个步骤中做到这一点我认为:

  1. Get the user's object ID 获取用户的对象ID

     ObjectId id = userObj.getId(); 
  2. Get all comments with that user 获取该用户的所有评论

     Query q = ds.createQuery(Comment.class); q.field("user").equal("name"); q.retrievedFields(true, "_id"); // just get the IDs 
  3. Get all Blogs with those comments.. 获取包含这些评论的所有博客..

However , there are better ways: 但是 ,还有更好的方法:

  1. Embed Comments rather than reference them. 嵌入评论而不是引用它们。 They don't make much sense as a standalone object. 它们作为一个独立的对象没有多大意义。 Then you can do: 然后你可以这样做:

     Query q = ds.createQuery(Blog.class); q.field("comments.user").equal("name"); 
  2. Add a reference from Comments back to Blog - an ObjectId field called "blog" for example. 将评论中的引用添加回Blog - 例如,名为“blog”的ObjectId字段。 Then you can do: 然后你可以这样做:

     Query q = ds.createQuery(Comment.class); q.field("user").equal("name"); q.retrievedFields(true, "blog"); // only get the blog ObjectIds 

to get all the Blog object Ids, then load them in a further step. 获取所有Blog对象ID,然后再继续加载它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM