mongodb 查询 spring 键值数据
mongodb query with spring data for key-value
我已经开始使用 mongodb 和 spring 启动以及 spring JPA 数据的项目,我意识到我无法将我的数据模型映射到实体并对其进行查询很容易,所以我有两个问题,
我的数据模型是这样的(仅针对一个 Collection)
{
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
}
- 我可以像我那样在 mongodb 集合中映射属性 属性 ( Map )
如何进行查询以查找属性?
我可以那样做吗?
List<User> findAllByAttributesAge(Integer age);
Can I map attributes property in my mongodb collection like I did ( Map )
是的,你可以,而且它可能对“" or "”模式有用(尽管很棘手)。
如果您事先知道您的架构,我强烈建议您将其显示在您的域对象中。看看here.
How can I make query for finding the attributes?
如果您不使用动态架构,属性 嵌套属性的遍历在 Spring Data MongoDB Reference Documentation.
中有清楚的解释
如果您使用动态架构,您很可能会使用 MongoDB JSON based query methods。
今天我在 Spring Mongodb 中遇到了地图查询问题,由于这个问题在 google 中出现了第一个问题,所以我将提供另一个答案。
由于其他答案引用了文档,而该文档没有太多信息,我将举例说明动态模式的 @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);
我已经开始使用 mongodb 和 spring 启动以及 spring JPA 数据的项目,我意识到我无法将我的数据模型映射到实体并对其进行查询很容易,所以我有两个问题,
我的数据模型是这样的(仅针对一个 Collection)
{
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
}
- 我可以像我那样在 mongodb 集合中映射属性 属性 ( Map )
如何进行查询以查找属性?
我可以那样做吗?
List<User> findAllByAttributesAge(Integer age);
Can I map attributes property in my mongodb collection like I did ( Map )
是的,你可以,而且它可能对“
如果您事先知道您的架构,我强烈建议您将其显示在您的域对象中。看看here.
How can I make query for finding the attributes?
如果您不使用动态架构,属性 嵌套属性的遍历在 Spring Data MongoDB Reference Documentation.
中有清楚的解释如果您使用动态架构,您很可能会使用 MongoDB JSON based query methods。
今天我在 Spring Mongodb 中遇到了地图查询问题,由于这个问题在 google 中出现了第一个问题,所以我将提供另一个答案。
由于其他答案引用了文档,而该文档没有太多信息,我将举例说明动态模式的 @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);