java實現MongoDB查詢一

        目前公司使用的數據庫主要是針對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();
    }


未完待續...





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章