我已经启动了一个带有mongodb和spring boot以及spring JPA数据的项目,我意识到我无法将我的数据模型映射到实体并对其进行简单的查询,所以我有两个问题,
我的数据模型就是这样(仅适用于一个集合)
{
name: "Name",
lastName: "Last Name",
attributes: {
age: 25
eye: {
color: "RED",
size: "BIG"
}
}
}
我的实体是
@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
}
List<User> findAllByAttributesAge(Integer age);
我可以像我一样映射我的mongodb集合中的属性属性(Map)
是的,你可以,并且它可能对“dynamic”或“partly defined”架构证明是有用的(虽然很棘手)。
如果您事先知道自己的架构,我强烈建议您在域对象中显示它。看看here。
如何查询查找属性?
如果不使用动态模式,则在Spring Data MongoDB Reference Documentation中会清楚地解释嵌套属性的属性遍历。
如果您使用动态模式,您很可能会使用MongoDB JSON based query methods。
今天我在Spring Mongodb中遇到了Map查询的问题,而且由于这个问题弹出谷歌中的第一个,我将提供另一个答案。
由于其他答案引用了文档,并且该文档没有很多信息,因此我将举例说明动态模式的@Query注释有多好:
@Query(value = "{'attributes.age' : ?0}")
List<User> findAllByAttributesAge(int age);
此外,您还可以查询眼睛颜色:
@Query(value = "{'attributes.eye.color' : ?0}")
List<User> findAllByAttributesEyeColor(String color);
正如文档所说的其他答案,您可以过滤结果,只接收您喜欢的文档部分:
// 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);