首页 > 解决方案 > 如何从 MongoDB 中检索特定的元素列表?

问题描述

我想从 Mongodb 表中检索特定的元素列表。

假设我的 Employee 类中有两个变量:

public Class Employee
{
private String Id;
private String Name;
.
.

现在,当我进行 fetch 查询时,它将类似于 -:

List<Employee> list=mongoTemplate.findAll();

然后我将遍历每个员工对象以获取员工 ID 并保存在List<String>

现在,我想要这样一种解决方案,即我可以一次检索所有 ID。类似于-:

List<String> employeeId = someCodeHere; 

如果可以的话请帮忙

提前致谢。

标签: javamongodbspring-boot

解决方案


根据Mongos Reference documentation on distinct operation:

在单个集合或视图中查找指定字段的不同值,并在数组中返回结果。

在 Spring Data MongoDB 中,可以这样实现:

DistinctIterable<String> distinctIds =
    mongoTemplate.getCollection(mongoTemplate.getCollectionName(Employee.class))
    .distinct("id", String.class);

return Lists.newArrayList(distinctIds);

// or

BasicDBObject dbObject = new BasicDBObject();
dbObject.append("name", new BasicDBObject("$regex", ".*and.*"));

DistinctIterable<String> distinctIds =
    mongoTemplate.getCollection(mongoTemplate.getCollectionName(Employee.class))
    .distinct("id", dbObject, String.class);

return Lists.newArrayList(distinctIds);

MongoTemplate 在这里提供了一些不同的重载。初级查询将直接收集员工集合条目的所有 ID,而后者将仅对and名称中包含的员工 ID 执行过滤。

为了将可迭代的结果集转换为请求的字符串对象列表,您可以使用Guava 的newArray(...)特性

正如@Veeram 在他的评论中也提到的那样,您当然也可以使用投影查询,例如

Query query = Query.query(Criteria.where(...));
query.fields().include("id");

return mongoTemplate.find(query, String.class);

wherequery.fields().include("id")用于指定您实际感兴趣的字段。

与 相比distinct,此方法将在结果列表中包含重复条目(如果有的话)。虽然 ID 通常应该是唯一的,但是对名称执行这两个查询可能会产生包含多个相同条目的结果。

虽然@Boris 给出的答案在技术上也是有效的,但不幸的是,它可能会对性能产生一些影响,特别是如果还需要检索大量嵌入和引用的文档。因此,我不推荐这种方法。

最后说明:在整个示例中,我将IdandName字段保留为小写字母,因为这基本上是Java 命名约定


推荐阅读