2

I have multiple datasource in my application (mysql and mongodb) and i am using JpaRepository (spring data jpa) and MongoRepository (spring data mongo ) respectively.

The below code works for getting all the imei numbers from the vehicle table(mysql)

@Repository
public interface VehicleRepo extends JpaRepository<Vehicle, Long>{
    @Query(value = "SELECT imei FROM vehicle", nativeQuery = true)
    public List<Object[]> findImei();
}

I have another mongo repo like below.

@Repository
public interface DeviceRepo extends MongoRepository<Device, String>{
    // looking for a method which returns all the distinct imei
}

I want to know what what would be the query in mongodb.

(My requirement is to select all the only distinct imei field from the Device and only single field selection like VehicleRepo)

I have tried multiple combinations but none worked.

Alien
  • 15,141
  • 6
  • 37
  • 57

3 Answers3

4

May be a little bit late but i am doing the same thing: If your collection just have a String (datatype) Field in it and you want to get this field only, you can try:

    @Query(value = "{ 'groupId' :  ?0 }", fields = "{ '_id': 0, 'user.$id':1 }")
    List<String> findAllUserIdByGroupId(String groupId);

the value mean query and the fields type is what you want to get / ignore

In mongo db you can check with this site (https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/)

or an answer in Stackoverflow (Spring Data Mongo Query Field parameters)

Nam Nguyễn
  • 552
  • 4
  • 20
1

I could not find any solution using the @Query so i had to use MongoTemplate to achieve the same.

DistinctIterable<String> iterableObject= mongoTemplate.getCollection("collectionName").distinct("fieldName",String.class);
Iterator<String> iter = iterableObject.iterator();      
while(iter.hasNext()){
    System.out.println(iter.next());
}
Alien
  • 15,141
  • 6
  • 37
  • 57
1

You can also use the mongoTemplate in a custom repository method to achieve same thing (similar to Alien's) response above:

 List<String> imeiList = mongoTemplate.query(Device.class)
.distinct("imei")
.as(String.class)
.all();

More info in latest spring-data-mongo docs: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.query.distinct

Felby
  • 4,045
  • 4
  • 26
  • 23