Morphine query based on one field of a deeply nested object

I want to get an object based on the id (or another separate field) of an object that is nested 2 levels from the object I want to get. Demo example:

I want to find all blog posts that have been commented on by a specific user.

Blog List<Comment> ignoredField1 ignoredField2 User id name ignoredField3 

Comments and users @Referenced by their parent objects.

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

I understand how to find blogs with comments, where ignoredField1 / 2 has a certain meaning, but I want to navigate further.

I tried the following, but since all comment fields are compared, there is no match

 q.field("comments").hasThisElement(new Comment(new User("name"))); 
+4
source share
1 answer

You need to do this in a few steps, I think:

  • Get user object id

     ObjectId id = userObj.getId(); 
  • Get comments for this user

     Query q = ds.createQuery(Comment.class); q.field("user").equal("name"); q.retrievedFields(true, "_id"); // just get the IDs 
  • Get all blogs with these comments.

However, there are better ways:

  • Insert comments, not link to them. They do not make much sense as a separate entity. Then you can do:

     Query q = ds.createQuery(Blog.class); q.field("comments.user").equal("name"); 
  • Add the link from the comments back to the blog — for example, an ObjectId field called a “blog”. 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, and then download them in the next step.

+3
source

Source: https://habr.com/ru/post/1390000/


All Articles