Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

After reading this post 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.

I have tried the following but because all Comment fields are compared, there is no match

q.field("comments").hasThisElement(new Comment(new User("name")));
like image 523
Toby Avatar asked Jan 09 '12 06:01

Toby


1 Answers

You'll have to do it in a fews of steps I think:

  1. Get the user's object 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. 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.

like image 56
Nic Cottrell Avatar answered Sep 29 '22 07:09

Nic Cottrell