文档菜单
文档首页
/ / /
Java 同步驱动程序
/

检索字段的唯一值

您可以通过调用distinct() 方法在 MongoCollection 对象上检索集合中字段的唯一值列表。将文档字段名称作为第一个参数传递,并将您想将结果转换成的类作为第二个参数传递,如下所示

collection.distinct("countries", String.class);

您可以使用点表示法指定文档中的字段或嵌套文档中的字段。以下方法调用返回 awards 嵌套文档中 wins 字段的每个唯一值

collection.distinct("awards.wins", Integer.class);

您可以可选地传递一个查询过滤器给该方法,以限制 MongoDB 实例检索唯一值的文档集,如下所示

collection.distinct("type", Filters.eq("languages", "French"), String.class);

distinct() 方法返回一个实现 DistinctIterable 接口的对象。此接口包含访问、组织和遍历结果的方法。它还继承自其父接口 MongoIterable 中的方法,例如 first(),它返回第一个结果,以及 cursor(),它返回一个 MongoCursor 实例。

以下代码片段检索 movies 集合中 year 文档字段的唯一值列表。它使用查询过滤器匹配包含 "Carl Franklin" 作为 directors 数组中值的电影。

注意

此示例使用连接 URI 连接到 MongoDB 实例。有关连接到您的 MongoDB 实例的更多信息,请参阅连接指南.

// Retrieves distinct values of a field by using the Java driver
package usage.examples;
import org.bson.Document;
import com.mongodb.MongoException;
import com.mongodb.client.DistinctIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class Distinct {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
try {
// Retrieves the distinct values of the "year" field present in documents that match the filter
DistinctIterable<Integer> docs = collection.distinct("year", Filters.eq("directors", "Carl Franklin"), Integer.class);
MongoCursor<Integer> results = docs.iterator();
// Prints the distinct "year" values
while(results.hasNext()) {
System.out.println(results.next());
}
// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("An error occurred: " + me);
}
}
}
}

当您运行此示例时,您应该会看到报告所有包含 Carl Franklin 作为导演的电影的每个唯一年份的输出,如下所示

1992
1995
1998
...

提示

旧版 API

如果您正在使用旧版 API,请参阅我们的常见问题解答页面了解您需要对此代码示例进行哪些更改。

有关此页面上提到的类和方法的更多信息,请参阅以下资源

  • distinct() API 文档

  • DistinctIterable API 文档

  • 点表示法 服务器手册条目

  • MongoIterable API 文档

返回

计数文档

© . All rights reserved.