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")));
You'll have to do it in a fews of steps I think:
Get the user's object ID
ObjectId id = userObj.getId();
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
Get all Blogs with those comments..
However, there are better ways:
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With