简体   繁体   English

如何使用 Spring 数据 MongoDB 查询生成获取所有 object id 的列表

[英]How to get list of all object ids with Spring Data MongoDB query generation

How do I get a list of object IDs back from Spring Data MongoDB's automatic query generation?如何从 Spring Data MongoDB 的自动查询生成中获取 object ID 的列表?

I'm expecting something like我期待类似的东西

public interface EntityRepo extends Repository<Entity, ObjectId> {
  List<ObjectId> findDistinctIdBy()
}

But executing that query throws an exception that it can't parse the json.但是执行该查询会引发一个异常,它无法解析 json。 And the json returned is the full Entity object.并且返回的 json 是完整的实体 object。

I can already do this with a @Query annotation specifying a projection, or using the MongoTemplate distinct() or aggregate().我已经可以使用指定投影的@Query 注释或使用 MongoTemplate distinct() 或 aggregate() 来做到这一点。 But I'm specifically looking for the automatic way to do this with their query generation syntax.但我特别在寻找使用他们的查询生成语法自动执行此操作的方法。

According to Spring Data MongoDB Query Creation , you can use the Distinct keyword.根据Spring Data MongoDB Query Creation ,可以使用 Distinct 关键字。 Maybe this is where my assumptions go wrong, but I'd expect that to return the distinct list of ObjectID or fields values, not the full documents.也许这就是我的假设 go 错误的地方,但我希望返回不同的 ObjectID 或字段值列表,而不是完整的文档。 In mongosh db.coll.distinct() query will return the array of matching values for a given field.在 mongosh db.coll.distinct() 查询将返回给定字段的匹配值数组。 And you obviously have to specify the field.而且您显然必须指定该字段。 Something like db.coll.distinct('_id', {}, {}) will return类似 db.coll.distinct('_id', {}, {}) 的东西会返回

[ ObjectId("507f1f77bcf86cd799439011") ]

I just want that result back.我只是想要那个结果。

Distinct will return only unique documents by some rule but it still will be List<Entity> . Distinct将根据某些规则仅返回唯一文档,但仍将是List<Entity> You can combine method with @Query annotation.您可以将方法与@Query注释结合使用。

@Query(fields = {"_id"})
List<Entity> findAll();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM