mongodb query with spring data for key-value

15,516

Solution 1

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.

Solution 2

Today I had a problem with Map query in Spring Mongodb, and since this question pops the first one in google I will provide another answer.

Since the other answer references to documentation, and that documentation does not have a lot of information, I am going to put an example of how good is the @Query annotation for dynamic schema:

@Query(value = "{'attributes.age' : ?0}")
List<User> findAllByAttributesAge(int age);

Also, you could query eye color, too:

@Query(value = "{'attributes.eye.color' : ?0}")
List<User> findAllByAttributesEyeColor(String color);

As the other answers documentation says, you could filter the result, and receive only the part of the document that you prefer:

// It will return the users with only name and last name
@Query(value = "{'attributes.age' : ?0}", fields = "{ name : 1, lastName : 1 }")
List<User> findAllByAttributesAge(int age);
Share:
15,516
navid_gh
Author by

navid_gh

Updated on June 13, 2022

Comments

  • navid_gh
    navid_gh almost 2 years

    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);