Distinct in Spring Data MongoDB

前端 未结 7 1649
小鲜肉
小鲜肉 2021-01-04 00:28

Has anyone tried incorporating distinct in their query using Spring Data for Mongo. If you have an example can you please post it. Where and how sh

7条回答
  •  时光说笑
    2021-01-04 00:47

    After a little poking around, I have come up with the following solution, which is OK and works, but can probably be improved upon. I am still pretty new to Spring, so if you have a better idea, then please do let me know.

    Anyway, here it is:

    First off, we use the @Autowired annotation to bring in the base MongoTemplate from spring-data-mongodb

    @Autowired
    MongoTemplate mongoTemplate;
    

    Once we have that, we can use it to make some queries. Note that this is the slightly smelly part because you have to tell Spring what the return type is and it doesn’t really like that…

    // Get the distinct stuff from MongoDB
    List coll = mongoTemplate.getCollection("mycollection").distinct("myfield");
    

    In the above code you will notice that I have defined a List type variable called coll that uses the @Autowired MongoTemplate variable to get a collection and then a field using distinct. This is analogous to db.whatever.distinct("term") on the Mongo shell.

提交回复
热议问题