java - 如何从 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;
如果可以的话请帮忙
提前致谢。
解决方案
根据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 给出的答案在技术上也是有效的,但不幸的是,它可能会对性能产生一些影响,特别是如果还需要检索大量嵌入和引用的文档。因此,我不推荐这种方法。
最后说明:在整个示例中,我将Id
andName
字段保留为小写字母,因为这基本上是Java 命名约定。
推荐阅读
- python - 在 OSmnx 中将图形投影到 espg:4326 上的最快方法
- javascript - 旅行商问题实现语言
- mongodb - MongoDB 在许多字段上按日期聚合
- java - 即使在完成样本测试用例后也无法得到正确答案
- google-apps-script - 嵌入在谷歌表中的谷歌脚本添加一个菜单项
- python-3.x - 如何在列表列表中查找值的频率并通过共同值与另一个现有列表组合?
- wpf - 调整 WPF 图表工具包 ColumnSeries (System.Windows.Controls.DataVisualization.Charting)
- javascript - 反应:无法使用索引访问组件状态中的数组数据
- javascript - 如何让我的自动图像轮播循环回到第一个图像而不暴露第二个图像
- python - Docker构建不安装依赖项