Mongodb去重查询

最近工作中用到Mongodb,于是花时间学习了一下,简单入门

回归正题,简单的查询、修改、删除就不说了哈。

去重查询

//1.连接数据库,若存在即选中,若不存在就建立
MongoDatabase mongoDatabase  = DbUtils.getMongoDatabase();
//2.获取连接
MongoCollection mongoCollection = mongoDatabase.getCollection("数据库名");
//去重查询
DistinctIterable distinct = mongoCollection.distinct("deviceAdd",Filters.eq("functionCode", functionCode), String.class);

MongoCursor cur = distinct.iterator();
while (cur.hasNext()){
    try {
            list.add(Integer.valueOf(cur.next()));
        } catch (Exception e){
            e.printStackTrace();
        }
}

Dbutils类

public class DbUtils {
    private static MongoDatabase db;


    //获取mogodb数据库
    public static MongoDatabase getMongoDatabase(){
        try {
            InputStream stream = DbUtils.class.getResourceAsStream("/dbconfig.properties");
            Properties properties = new Properties();
            properties.load(stream);
            MongoClientOptions option = MongoClientOptions.builder().connectTimeout(60000).threadsAllowedToBlockForConnectionMultiplier(10).connectionsPerHost(100).build();
            MongoClient monGoClient = new MongoClient(new ServerAddress(properties.getProperty("mongodb.serverUrl"), Integer.valueOf(properties.getProperty("mongodb.port"))), option);
            //获取操作数据库
            db = monGoClient.getDatabase(properties.getProperty("mongodb.database"));
        } catch (Exception e){
            e.printStackTrace();
        }
        return db;
    }
}

dbconfig.properties

#mongodb配置
mongodb.serverUrl = 127.0.0.1
mongodb.port = 27017
mongodb.database = mqttDb
mongodb.connectionTimeout = 60000
mongodb.socketTimeout = 60000

DistinctIterable distinct = mongoCollection.distinct("去重字段名",查询条件, type类型);

这样就能得到去重后的查询数据咯

你可能感兴趣的:(数据库学习,mongodb,数据库,java,spring)