0

How i can translate this basic sentence to mongotemplate or mongorepository I need find all distinct names in collection user

db.user.distinct('name');


@Document(collection = "user")
public class User {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Sample Json

 {
    "_id" : "12358",
    "name" : "HiMan",
    "description" : "sales category",
}
{
    "_id" : "791127",
    "name" : "HiMan",
    "description" : "",
}
{
    "_id" : "123123",
    "name" : "Rango",
    "description" : "sales Rango",
}

And i get: [ "Rango", "HiMan" ]

grondon
  • 161
  • 1
  • 7

1 Answers1

0

MongoRepository is pretty straight forward:

public interface UserMongoRepository extends MongoRepository<User, String> {     
}

Replace String with the type of your primary key. As far as methods are concerned, they follow a pretty easy pattern: findOneByName(String name); other options are findAll, findFirst, findDistinct etc.

So your repository may end up looking like:

public interface UserMongoRepository extends MongoRepository<User, String> {     
    User findDistinctByName(String name);
}

See the docs for more information.

Also, to address the differences between using a mongoRepository vs a mongoTemplate, check out this post

Robert H
  • 11,520
  • 18
  • 68
  • 110