Search code examples
javaspringmongodbspring-bootspring-data-mongodb

mongodb query with spring data for key-value


I've been started a project with mongodb and spring boot and spring JPA data and I realised I cannot map my data model to entity and make a query on that easily, so I have two questions,

My data model is like that ( just for one Collection )

{
   name: "Name",
   lastName: "Last Name",
   attributes: {
      age: 25
      eye: {
         color: "RED",
         size: "BIG"
      }
   }
}

And my entity is

@Entity // or @Document
public class User{
   private String name;
   private String lastName;
   private Map<String, ?> attributes = new HashMap<>();

   // id or the setter getter are omitted
}
  1. Can I map attributes property in my mongodb collection like I did ( Map )
  2. How can I make query for finding the attributes?

    Can I do it like that? List<User> findAllByAttributesAge(Integer age);


Solution

  • Can I map attributes property in my mongodb collection like I did ( Map )

    Yes, you can, and it may prove useful (though tricky) for a "dynamic" or "partly defined" schema.

    If you know your schema in advance, I strongly recommend that it shows in your domain object. Take a look here.

    How can I make query for finding the attributes?

    If you don't use a dynamic schema, property traversal for nested properties is clearly explained in the Spring Data MongoDB Reference Documentation.

    If you use dynamic schema, you'll most probably use MongoDB JSON based query methods.