此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Data MongoDB 4.4.0spring-doc.cadn.net.cn

查询文档

您可以使用QueryCriteria类来表达您的查询。 它们具有镜像原生 MongoDB 运算符名称的方法名称,例如lt,lte,is等。 这QueryCriteria类遵循 Fluent API 样式,因此您可以将多个方法条件和查询链接在一起,同时拥有易于理解的代码。 为了提高可读性,静态导入允许您避免使用 'new' 关键字来创建QueryCriteria实例。 您还可以使用BasicQuery创建Query实例,如以下示例所示:spring-doc.cadn.net.cn

示例 1.从纯 JSON 字符串创建 Query 实例
BasicQuery query = new BasicQuery("{ age : { $lt : 50 }, accounts.balance : { $gt : 1000.00 }}");
List<Person> result = mongoTemplate.find(query, Person.class);

查询集合中的文档

之前,我们了解了如何使用findOnefindById方法MongoTemplate. 这些方法以正确的方式返回单个域对象,或者使用响应式 API aMono发出单个元素。 我们还可以查询要作为域对象列表返回的文档集合。 假设我们有大量的Person具有 name 和 age 的对象作为文档存储在集合中,并且每个人都有一个带有余额的嵌入式帐户文档,我们现在可以使用以下代码运行查询:spring-doc.cadn.net.cn

使用 MongoTemplate 查询文档
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

// ...

List<Person> result = template.query(Person.class)
  .matching(query(where("age").lt(50).and("accounts.balance").gt(1000.00d)))
  .all();
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

// ...

Flux<Person> result = template.query(Person.class)
  .matching(query(where("age").lt(50).and("accounts.balance").gt(1000.00d)))
  .all();

所有 find 方法都采用Queryobject 作为参数。 此对象定义用于执行查询的条件和选项。 这些条件通过使用Criteria对象,该对象具有名为where要实例化新的Criteria对象。 我们建议对org.springframework.data.mongodb.core.query.Criteria.whereQuery.query使查询更具可读性。spring-doc.cadn.net.cn

查询应返回一个ListFluxPerson满足指定条件的对象。 本节的其余部分列出了CriteriaQuery对应于 MongoDB 中提供的运算符的类。 大多数方法都会返回Criteriaobject 为 API 提供 Fluent 样式。spring-doc.cadn.net.cn

Criteria 类的方法

Criteriaclass 提供了以下方法,所有这些方法都对应于 MongoDB 中的运算符:spring-doc.cadn.net.cn

Criteria 类还为地理空间查询提供了以下方法。spring-doc.cadn.net.cn

  • Criteria (Circle circle)使用 创建 Geospatial 准则$geoWithin $center运营商。spring-doc.cadn.net.cn

  • Criteria (Box box)使用$geoWithin $box操作。spring-doc.cadn.net.cn

  • Criteria 其中 (Circle circle)使用 创建 Geospatial 准则$geoWithin $center运营商。spring-doc.cadn.net.cn

  • Criteria (Point point)使用$near操作spring-doc.cadn.net.cn

  • Criteria 近球体 (Point point)使用 创建 Geospatial 准则$nearSphere$center操作。这仅适用于 MongoDB 1.7 及更高版本。spring-doc.cadn.net.cn

  • Criteria minDistance (最小距离) (double minDistance)使用$minDistanceoperation,以便与 $near 一起使用。spring-doc.cadn.net.cn

  • Criteria maxDistance (double maxDistance)使用$maxDistanceoperation,以便与 $near 一起使用。spring-doc.cadn.net.cn

Queryclass 有一些额外的方法,允许选择某些字段以及限制和排序结果。spring-doc.cadn.net.cn

Query 类的方法

模板 API 允许直接使用结果投影,使您能够针对给定域类型映射查询,同时将作结果投影到另一个域,如下所述。spring-doc.cadn.net.cn

class

template.query(SWCharacter.class)
    .as(Jedi.class)

有关结果投影的更多信息,请参阅文档的 Projections 部分。spring-doc.cadn.net.cn

选择字段

MongoDB 支持投影查询返回的字段。 投影可以包含和排除字段 (_id字段始终包含在内),具体取决于其名称。spring-doc.cadn.net.cn

示例 2.选择结果字段
public class Person {

    @Id String id;
    String firstname;

    @Field("last_name")
    String lastname;

    Address address;
}

query.fields().include("lastname");              (1)

query.fields().exclude("id").include("lastname") (2)

query.fields().include("address")                (3)

query.fields().include("address.city")           (4)
1 Result 将同时包含两者_idlast_name通过{ "last_name" : 1 }.
2 Result 将仅包含last_name通过{ "_id" : 0, "last_name" : 1 }.
3 Result 将包含_id和整个address对象通过{ "address" : 1 }.
4 Result 将包含_id以及address对象,该对象仅包含city字段通过{ "address.city" : 1 }.

从 MongoDB 4.4 开始,您可以将聚合表达式用于字段投影,如下所示:spring-doc.cadn.net.cn

例 3.使用表达式计算结果字段
query.fields()
  .project(MongoExpression.create("'$toUpper' : '$last_name'"))         (1)
  .as("last_name");                                                     (2)

query.fields()
  .project(StringOperators.valueOf("lastname").toUpper())               (3)
  .as("last_name");

query.fields()
  .project(AggregationSpELExpression.expressionOf("toUpper(lastname)")) (4)
  .as("last_name");
1 使用本机表达式。使用的字段名称必须引用数据库文档中的字段名称。
2 分配表达式结果投影到的字段名称。生成的字段名称不会映射到域模型。
3 使用AggregationExpression.非本机MongoExpression,字段名称将映射到域模型中使用的字段名称。
4 将 SpEL 与AggregationExpression调用表达式函数。字段名称将映射到域模型中使用的字段名称。

@Query(fields="…")允许在Repository级别,如 MongoDB 基于 JSON 的查询方法和字段限制中所述。spring-doc.cadn.net.cn

其他查询选项

MongoDB 提供了多种将元信息(如注释或批处理大小)应用于查询的方法。使用Query应用程序接口 这些选项直接有几种方法。spring-doc.cadn.net.cn

提示

索引提示可以通过两种方式应用,即使用索引名称或其字段定义。spring-doc.cadn.net.cn

template.query(Person.class)
    .matching(query("...").withHint("index-to-use"));

template.query(Person.class)
    .matching(query("...").withHint("{ firstname : 1 }"));

游标批处理大小

游标批处理大小定义每个响应批处理中要返回的文档数。spring-doc.cadn.net.cn

Query query = query(where("firstname").is("luke"))
    .cursorBatchSize(100)

排序规则

将排序规则与集合作一起使用是指定Collationinstance 中,如以下两个示例所示:spring-doc.cadn.net.cn

Collation collation = Collation.of("de");

Query query = new Query(Criteria.where("firstName").is("Amél"))
    .collation(collation);

List<Person> results = template.find(query, Person.class);

读取首选项

ReadPreference可以直接在Query对象,如下所述运行。spring-doc.cadn.net.cn

template.find(Person.class)
    .matching(query(where(...)).withReadPreference(ReadPreference.secondary()))
    .all();
Query实例将取代默认的ReadPreferenceMongoTemplate.

评论

查询可以配备注释,这使得它们更容易在服务器日志中查找。spring-doc.cadn.net.cn

template.find(Person.class)
    .matching(query(where(...)).comment("Use the force luke!"))
    .all();

查询非重复值

MongoDB 提供了一个作,通过使用结果文档中的查询来获取单个字段的不同值。 结果值不需要具有相同的数据类型,该功能也不限于简单类型。 对于检索,实际结果类型对于转换和键入很重要。以下示例演示如何查询非重复值:spring-doc.cadn.net.cn

示例 4.检索非重复值
template.query(Person.class)  (1)
  .distinct("lastname")       (2)
  .all();                     (3)
1 查询Person收集。
2 选择lastname田。字段名称根据 domain types 属性声明进行映射,将@Fieldannotations 中。
3 将所有非重复值检索为ListObject(由于未指定显式结果类型)。

将非重复值检索到CollectionObject是最灵活的方法,因为它会尝试确定域类型的属性值并将结果转换为所需的类型或映射Document结构。spring-doc.cadn.net.cn

有时候,当 desired field 的所有值都固定为某种类型时,直接获取一个正确类型的Collection,如以下示例所示:spring-doc.cadn.net.cn

例 5.检索强类型非重复值
template.query(Person.class)  (1)
  .distinct("lastname")       (2)
  .as(String.class)           (3)
  .all();                     (4)
1 查询Person.
2 选择lastname田。fieldname 根据 domain types 属性声明进行映射,将@Fieldannotations 中。
3 检索到的值将转换为所需的目标类型 — 在本例中为String.如果存储的字段包含文档,也可以将值映射到更复杂的类型。
4 将所有非重复值检索为ListString.如果该类型无法转换为所需的目标类型,此方法会抛出一个DataAccessException.

+= 地理空间查询spring-doc.cadn.net.cn

MongoDB 通过使用运算符(如$near,$within,geoWithin$nearSphere.特定于地理空间查询的方法可在Criteria类。还有一些 shape 类 (Box,CirclePoint) 与地理空间相关Criteria方法。spring-doc.cadn.net.cn

在 MongoDB 事务中使用地理空间查询时需要注意,请参阅事务内的特殊行为

要了解如何执行地理空间查询,请考虑以下事项Venue类(取自集成测试并依赖于丰富的MappingMongoConverter):spring-doc.cadn.net.cn

Venue.java
@Document(collection="newyork")
public class Venue {

  @Id
  private String id;
  private String name;
  private double[] location;

  @PersistenceConstructor
  Venue(String name, double[] location) {
    super();
    this.name = name;
    this.location = location;
  }

  public Venue(String name, double x, double y) {
    super();
    this.name = name;
    this.location = new double[] { x, y };
  }

  public String getName() {
    return name;
  }

  public double[] getLocation() {
    return location;
  }

  @Override
  public String toString() {
    return "Venue [id=" + id + ", name=" + name + ", location="
        + Arrays.toString(location) + "]";
  }
}

要在Circle,您可以使用以下查询:spring-doc.cadn.net.cn

Circle circle = new Circle(-73.99171, 40.738868, 0.01);
List<Venue> venues =
    template.find(new Query(Criteria.where("location").within(circle)), Venue.class);

要在Circle使用 Spherical Coordinates,您可以使用以下查询:spring-doc.cadn.net.cn

Circle circle = new Circle(-73.99171, 40.738868, 0.003712240453784);
List<Venue> venues =
    template.find(new Query(Criteria.where("location").withinSphere(circle)), Venue.class);

要在Box,您可以使用以下查询:spring-doc.cadn.net.cn

//lower-left then upper-right
Box box = new Box(new Point(-73.99756, 40.73083), new Point(-73.988135, 40.741404));
List<Venue> venues =
    template.find(new Query(Criteria.where("location").within(box)), Venue.class);

要查找附近的场地Point,您可以使用以下查询:spring-doc.cadn.net.cn

Point point = new Point(-73.99171, 40.738868);
List<Venue> venues =
    template.find(new Query(Criteria.where("location").near(point).maxDistance(0.01)), Venue.class);
Point point = new Point(-73.99171, 40.738868);
List<Venue> venues =
    template.find(new Query(Criteria.where("location").near(point).minDistance(0.01).maxDistance(100)), Venue.class);

要查找附近的场地Point使用 Spherical Coordinates,您可以使用以下查询:spring-doc.cadn.net.cn

Point point = new Point(-73.99171, 40.738868);
List<Venue> venues =
    template.find(new Query(
        Criteria.where("location").nearSphere(point).maxDistance(0.003712240453784)),
        Venue.class);

Geo-near 查询

在 2.2 中更改!
MongoDB 4.2 删除了对
geoNear命令,该命令之前用于运行NearQuery.spring-doc.cadn.net.cn

Spring Data MongoDB 2.2 版MongoOperations#geoNear使用$geoNear 聚合,而不是geoNear命令运行NearQuery.spring-doc.cadn.net.cn

计算出的距离(dis使用 geoNear 命令时)现在嵌入了之前在包装器类型中返回的 添加到生成的文档中。 如果给定的域类型已包含具有该名称的属性,则计算的距离 被命名为calculated-distance带有可能随机的后缀。spring-doc.cadn.net.cn

目标类型可能包含一个以返回的距离命名的属性,以便(另外)将其直接读回域类型,如下所示。spring-doc.cadn.net.cn

GeoResults<VenueWithDistanceField> = template.query(Venue.class) (1)
    .as(VenueWithDistanceField.class)                            (2)
    .near(NearQuery.near(new GeoJsonPoint(-73.99, 40.73), KILOMETERS))
    .all();
1 用于标识目标集合和潜在查询映射的域类型。
2 目标类型包含distype 字段Number.

MongoDB 支持查询数据库以获取地理位置,并同时计算与给定起点的距离。使用地理位置接近查询,您可以表达诸如“查找周围 10 英里内的所有餐馆”之类的查询。为了让您这样做,MongoOperations提供geoNear(…)采用NearQuery作为参数(以及已经熟悉的实体类型和集合)进行设置,如以下示例所示:spring-doc.cadn.net.cn

Point location = new Point(-73.99171, 40.738868);
NearQuery query = NearQuery.near(location).maxDistance(new Distance(10, Metrics.MILES));

GeoResults<Restaurant> = operations.geoNear(query, Restaurant.class);

我们使用NearQuerybuilder API 设置查询以返回所有Restaurant给定Point到 10 英里。 这Metrics这里使用的 enum 实际上实现了一个接口,以便其他指标也可以插入到一个距离中。 一个Metric由乘数支持,用于将给定度量的距离值转换为本机距离。 此处显示的示例将 10 视为英里。使用内置量度之一(英里和公里)会自动触发在查询上设置的球形标志。 如果您想避免这种情况,请将 plaindouble值转换为maxDistance(…). 有关更多信息,请参阅 JavadocNearQueryDistance.spring-doc.cadn.net.cn

geo-near作返回一个GeoResultswrapper 对象,该对象封装了GeoResult实例。 包皮GeoResults允许访问所有结果的平均距离。 单个GeoResultobject 包含找到的实体加上它与原点的距离。spring-doc.cadn.net.cn

GeoJSON 支持

MongoDB 支持地理空间数据的 GeoJSON 和简单(传统)坐标对。这些格式都可用于存储和查询数据。请参阅有关 GeoJSON 支持的 MongoDB 手册,了解要求和限制。spring-doc.cadn.net.cn

域类中的 GeoJSON 类型

在域类中使用 GeoJSON 类型非常简单。这org.springframework.data.mongodb.core.geopackage 包含如下类型GeoJsonPoint,GeoJsonPolygon等。这些类型是扩展现有的org.springframework.data.geo类型。以下示例使用GeoJsonPoint:spring-doc.cadn.net.cn

public class Store {

	String id;

	/**
	 * { "type" : "Point", "coordinates" : [ x, y ] }
	 */
	GeoJsonPoint location;
}

如果coordinates的 GeoJSON 对象表示纬度经度对,则经度在前,然后是纬度
GeoJsonPoint因此治疗getX()作为 longitudegetY()作为纬度spring-doc.cadn.net.cn

存储库查询方法中的 GeoJSON 类型

使用 GeoJSON 类型作为存储库查询参数会强制使用$geometry运算符,如下例所示:spring-doc.cadn.net.cn

public interface StoreRepository extends CrudRepository<Store, String> {

	List<Store> findByLocationWithin(Polygon polygon);  (1)

}

/*
 * {
 *   "location": {
 *     "$geoWithin": {
 *       "$geometry": {
 *         "type": "Polygon",
 *         "coordinates": [
 *           [
 *             [-73.992514,40.758934],
 *             [-73.961138,40.760348],
 *             [-73.991658,40.730006],
 *             [-73.992514,40.758934]
 *           ]
 *         ]
 *       }
 *     }
 *   }
 * }
 */
repo.findByLocationWithin(                              (2)
  new GeoJsonPolygon(
    new Point(-73.992514, 40.758934),
    new Point(-73.961138, 40.760348),
    new Point(-73.991658, 40.730006),
    new Point(-73.992514, 40.758934)));                 (3)

/*
 * {
 *   "location" : {
 *     "$geoWithin" : {
 *        "$polygon" : [ [-73.992514,40.758934] , [-73.961138,40.760348] , [-73.991658,40.730006] ]
 *     }
 *   }
 * }
 */
repo.findByLocationWithin(                              (4)
  new Polygon(
    new Point(-73.992514, 40.758934),
    new Point(-73.961138, 40.760348),
    new Point(-73.991658, 40.730006)));
1 使用 commons 类型的存储库方法定义允许使用 GeoJSON 和旧格式调用它。
2 使用 GeoJSON 类型来使用$geometry算子。
3 请注意,GeoJSON 多边形需要定义一个封闭的环。
4 使用旧版格式$polygon算子。

度量和距离计算

然后是 MongoDB$geoNear运算符允许使用 GeoJSON Point 或旧坐标对。spring-doc.cadn.net.cn

NearQuery.near(new Point(-73.99171, 40.738868))
{
  "$geoNear": {
    //...
    "near": [-73.99171, 40.738868]
  }
}
NearQuery.near(new GeoJsonPoint(-73.99171, 40.738868))
{
  "$geoNear": {
    //...
    "near": { "type": "Point", "coordinates": [-73.99171, 40.738868] }
  }
}

尽管语法不同,但无论集合中的目标 Document 是什么格式,服务器都可以接受两者 正在使用。spring-doc.cadn.net.cn

距离计算存在巨大差异。使用传统格式作 在地球上的弧度(如球体)上,而 GeoJSON 格式使用

为避免严重的头痛,请确保将Metric设置为所需的度量单位,以确保 distance 才能正确计算。spring-doc.cadn.net.cn

换句话说:spring-doc.cadn.net.cn

假设您有 5 个文档,如下所示:spring-doc.cadn.net.cn

{
    "_id" : ObjectId("5c10f3735d38908db52796a5"),
    "name" : "Penn Station",
    "location" : { "type" : "Point", "coordinates" : [  -73.99408, 40.75057 ] }
}
{
    "_id" : ObjectId("5c10f3735d38908db52796a6"),
    "name" : "10gen Office",
    "location" : { "type" : "Point", "coordinates" : [ -73.99171, 40.738868 ] }
}
{
    "_id" : ObjectId("5c10f3735d38908db52796a9"),
    "name" : "City Bakery ",
    "location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
}
{
    "_id" : ObjectId("5c10f3735d38908db52796aa"),
    "name" : "Splash Bar",
    "location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
}
{
    "_id" : ObjectId("5c10f3735d38908db52796ab"),
    "name" : "Momofuku Milk Bar",
    "location" : { "type" : "Point", "coordinates" : [ -73.985839, 40.731698 ] }
}

获取 400 米半径内的所有文档[-73.99171, 40.738868]使用 GeoJSON 的:spring-doc.cadn.net.cn

例 6.GeoNear 与 GeoJSON
{
    "$geoNear": {
        "maxDistance": 400, (1)
        "num": 10,
        "near": { type: "Point", coordinates: [-73.99171, 40.738868] },
        "spherical":true, (2)
        "key": "location",
        "distanceField": "distance"
    }
}

返回以下 3 个文档:spring-doc.cadn.net.cn

{
    "_id" : ObjectId("5c10f3735d38908db52796a6"),
    "name" : "10gen Office",
    "location" : { "type" : "Point", "coordinates" : [ -73.99171, 40.738868 ] }
    "distance" : 0.0 (3)
}
{
    "_id" : ObjectId("5c10f3735d38908db52796a9"),
    "name" : "City Bakery ",
    "location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
    "distance" : 69.3582262492474 (3)
}
{
    "_id" : ObjectId("5c10f3735d38908db52796aa"),
    "name" : "Splash Bar",
    "location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
    "distance" : 69.3582262492474 (3)
}
1 距中心点的最大距离(以米为单位)。
2 GeoJSON 始终在球体上运行。
3 距中心点的距离(以米为单位)。

现在,当使用传统坐标对时,如前所述对 Radians 进行作。所以我们使用Metrics#KILOMETERS when constructing the `$geoNear命令。这Metric确保 Distance Multiplier 设置正确。spring-doc.cadn.net.cn

例 7.具有传统坐标对的 GeoNear
{
    "$geoNear": {
        "maxDistance": 0.0000627142377, (1)
        "distanceMultiplier": 6378.137, (2)
        "num": 10,
        "near": [-73.99171, 40.738868],
        "spherical":true, (3)
        "key": "location",
        "distanceField": "distance"
    }
}

返回 3 个文档,就像 GeoJSON 变体一样:spring-doc.cadn.net.cn

{
    "_id" : ObjectId("5c10f3735d38908db52796a6"),
    "name" : "10gen Office",
    "location" : { "type" : "Point", "coordinates" : [ -73.99171, 40.738868 ] }
    "distance" : 0.0 (4)
}
{
    "_id" : ObjectId("5c10f3735d38908db52796a9"),
    "name" : "City Bakery ",
    "location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
    "distance" : 0.0693586286032982 (4)
}
{
    "_id" : ObjectId("5c10f3735d38908db52796aa"),
    "name" : "Splash Bar",
    "location" : { "type" : "Point", "coordinates" : [ -73.992491, 40.738673 ] }
    "distance" : 0.0693586286032982 (4)
}
1 距中心点的最大距离(以弧度为单位)。
2 距离乘数,因此我们得到 Kilometers 作为结果距离。
3 确保我们对 2d_sphere 索引进行作。
4 距中心点的距离(以公里为单位) - 取其乘以 1000 以匹配 GeoJSON 变体的

全文搜索

从 MongoDB 2.6 版本开始,您可以使用$text算子。特定于全文查询的方法和作在TextQueryTextCriteria.执行全文搜索时,请参阅 MongoDB 参考,了解其行为和限制。spring-doc.cadn.net.cn

在实际使用全文搜索之前,必须正确设置搜索索引。 有关如何创建索引结构的更多详细信息,请参阅 Text Index 。 以下示例显示如何设置全文搜索:spring-doc.cadn.net.cn

db.foo.createIndex(
{
  title : "text",
  content : "text"
},
{
  weights : {
              title : 3
            }
}
)

搜索coffee cake可以按如下方式定义和运行:spring-doc.cadn.net.cn

例 8.全文查询
Query query = TextQuery
  .queryText(new TextCriteria().matchingAny("coffee", "cake"));

List<Document> page = template.find(query, Document.class);

要根据weightsTextQuery.sortByScore.spring-doc.cadn.net.cn

例 9.全文查询 - 按分数排序
Query query = TextQuery
  .queryText(new TextCriteria().matchingAny("coffee", "cake"))
  .sortByScore() (1)
  .includeScore(); (2)

List<Document> page = template.find(query, Document.class);
1 使用 score 属性按触发.sort({'score': {'$meta': 'textScore'}}).
2 TextQuery.includeScore()将计算的相关性包含在结果的Document.

您可以通过在搜索词前加上前缀或使用-notMatching,如以下示例所示(请注意,这两行具有相同的效果,因此是多余的):spring-doc.cadn.net.cn

// search for 'coffee' and not 'cake'
TextQuery.queryText(new TextCriteria().matching("coffee").matching("-cake"));
TextQuery.queryText(new TextCriteria().matching("coffee").notMatching("cake"));

TextCriteria.matching按原样采用提供的术语。 因此,您可以通过将短语放在双引号之间来定义短语(例如\"coffee cake\")或使用TextCriteria.phrase.以下示例显示了定义短语的两种方法:spring-doc.cadn.net.cn

// search for phrase 'coffee cake'
TextQuery.queryText(new TextCriteria().matching("\"coffee cake\""));
TextQuery.queryText(new TextCriteria().phrase("coffee cake"));

您可以为$caseSensitive$diacriticSensitive通过使用 上的相应方法TextCriteria. 请注意,这两个可选标志已在 MongoDB 3.2 中引入,除非明确设置,否则不会包含在查询中。spring-doc.cadn.net.cn

按示例查询

Query by Example 可用于模板 API 级别的运行示例查询。spring-doc.cadn.net.cn

以下截图显示了如何通过示例进行查询:spring-doc.cadn.net.cn

类型化示例查询
Person probe = new Person();
probe.lastname = "stark";

Example example = Example.of(probe);

Query query = new Query(new Criteria().alike(example));
List<Person> result = template.find(query, Person.class);

默认情况下Example是严格类型的。这意味着映射的查询具有包含的类型匹配,从而将其限制为探测可分配类型。 例如,当坚持使用默认 type 键 (_class),则查询具有限制,例如 (_class : { $in : [ com.acme.Person] }).spring-doc.cadn.net.cn

通过使用UntypedExampleMatcher,则可以绕过默认行为并跳过类型限制。因此,只要字段名称匹配,几乎任何域类型都可以用作创建引用的探测器,如下例所示:spring-doc.cadn.net.cn

例 10.无类型化示例查询
class JustAnArbitraryClassWithMatchingFieldName {
  @Field("lastname") String value;
}

JustAnArbitraryClassWithMatchingFieldNames probe = new JustAnArbitraryClassWithMatchingFieldNames();
probe.value = "stark";

Example example = Example.of(probe, UntypedExampleMatcher.matching());

Query query = new Query(new Criteria().alike(example));
List<Person> result = template.find(query, Person.class);

当包含null值中的ExampleSpec,Spring Data Mongo 使用嵌入式文档匹配而不是点表示法属性匹配。 这样做会强制嵌入文档中的所有属性值和属性顺序进行精确文档匹配。spring-doc.cadn.net.cn

UntypedExampleMatcher如果要在单个集合中存储不同的实体或选择不编写类型提示,则可能是正确的选择。spring-doc.cadn.net.cn

此外,请记住,使用@TypeAlias需要预先初始化MappingContext.为此,请配置initialEntitySet设置为 ,以确保读取作的别名解析正确。spring-doc.cadn.net.cn

Spring Data MongoDB 支持不同的匹配选项:spring-doc.cadn.net.cn

StringMatcher选项
匹配 逻辑结果

DEFAULT(区分大小写)spring-doc.cadn.net.cn

{"firstname" : firstname}spring-doc.cadn.net.cn

DEFAULT(不区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: firstname, $options: 'i'}}spring-doc.cadn.net.cn

EXACT(区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: /^firstname$/}}spring-doc.cadn.net.cn

EXACT(不区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: /^firstname$/, $options: 'i'}}spring-doc.cadn.net.cn

STARTING(区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: /^firstname/}}spring-doc.cadn.net.cn

STARTING(不区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: /^firstname/, $options: 'i'}}spring-doc.cadn.net.cn

ENDING(区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: /firstname$/}}spring-doc.cadn.net.cn

ENDING(不区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: /firstname$/, $options: 'i'}}spring-doc.cadn.net.cn

CONTAINING(区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: /.*firstname.*/}}spring-doc.cadn.net.cn

CONTAINING(不区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: /.*firstname.*/, $options: 'i'}}spring-doc.cadn.net.cn

REGEX(区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: /firstname/}}spring-doc.cadn.net.cn

REGEX(不区分大小写)spring-doc.cadn.net.cn

{"firstname" : { $regex: /firstname/, $options: 'i'}}spring-doc.cadn.net.cn

查询集合以匹配 JSON Schema

您可以使用架构查询与 JSON 架构定义的给定结构匹配的文档的任何集合,如下例所示:spring-doc.cadn.net.cn

例 11.查询与$jsonSchema
MongoJsonSchema schema = MongoJsonSchema.builder().required("firstname", "lastname").build();

template.find(query(matchingDocumentStructure(schema)), Person.class);

请参阅 JSON 架构部分,了解有关 Spring Data MongoDB 中的架构支持的更多信息。spring-doc.cadn.net.cn