目前公司使用的数据库主要是针对MongoDB进行一些操作,特意在这里将这些常用操作列举出来,方便自己开发使用,也给新手们提供一些工具类里的方法,积累的多了就可封装成一个工具类提供大家开发使用了。没用Spring Data、Morphia等框架是为了减少学习、维护成本,还有直接JDBC的方式更加灵活。

        这一篇直接列举一些查询方法,以后遇到了会继续列举,至于连接数据的操作默认已经连接了,网上资料也很多。

1、获取collection对象 - 指定Collection


/**
     * 获取collection对象 - 指定Collection
     * @param collName
     * @return
     */
    public MongoCollection<Document> getCollection(String dbName, String collName) {
        if (null == collName || "".equals(collName)) {
            return null;
        }
        MongoCollection<Document> collection = mongoClient.getDatabase().getCollection(collName);
        return collection;
    }

2、查找对象 - 根据主键_id


/**
     * 查找对象 - 根据主键_id
     * @param collection
     * @param id
     * @return
     */
    public Document findById(MongoCollection<Document> coll, String id) {
        ObjectId _idobj = null;
        try {
            _idobj = new ObjectId(id);
        } catch (Exception e) {
            return null;
        }
        Document myDoc = coll.find(Filters.eq("_id", _idobj)).first();
        return myDoc;
    }


3、统计数


/** 统计数 */
    public int getCount(MongoCollection<Document> coll) {
        int count = (int) coll.count();
        return count;
    }


4、分页查询


/** 分页查询 */
    public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) {
        Bson orderBy = new BasicDBObject("_id", 1);
        return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();
    }


5、条件查询


/** 条件查询 */
    public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
        return coll.find(filter).iterator();
    }


未完待续...