如何从MongoDB中检索特定的元素列表?

瑞沙(Rishabh Bansal)

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

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

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

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

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

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

现在,我希望以一种可以一次性检索所有ID的方式解决问题。

List<String> employeeId = someCodeHere; 

如果可以的话请帮忙

提前致谢。

罗曼·沃特纳

根据《Mongos参考》文档中有关不同操作的说明:

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

在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进行过滤

为了将可迭代的结果集转换为请求的String对象列表,可以使用Guava的newArray(...)功能

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

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

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

其中,query.fields().include("id")用于指定的字段你真正感兴趣的。

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

虽然@Boris给出的答案在技术上也是有效的,但不幸的是,它可能会对性能产生一些影响,尤其是在还需要检索许多嵌入和引用文档的情况下。因此,我不建议采用这种方法。

最后要注意的是:在所有示例中,我Id和的Name字段都使用小写字母,因为这基本上是Java命名约定

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章