`
裴小星
  • 浏览: 260911 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
8ccf5db2-0d60-335f-a337-3c30d2feabdb
Java NIO翻译
浏览量:27563
F3e939f0-dc16-3d6e-8c0b-3315c810fb91
PureJS开发过程详解
浏览量:71860
07a6d496-dc19-3c71-92cf-92edb5203cef
MongoDB Java ...
浏览量:61964
社区版块
存档分类
最新评论

MongoDB Java Driver 源码分析(4):com.mongodb.DBCursor

阅读更多
  DBCurosr 是 DBCollection 的 find 方法返回的对象,可以设置 skip、limit 等属性之后,执行查询,得到查询结果,
  用法如下:
List<DBObject> obj
     = collection.find( query ).skip( 1000 ).limit( 100 ).toArray();

  DBCursor 类的方法可以可以分为两类:修改查询属性 和 执行查询。
  以上面的代码为例,find、skip、limit 就是修改查询属性,而 toArrray 就是执行查询。
  在实际的实现中,修改查询属性的方法实际上是修改 DBCursor 对象的属性,执行查询则是通过调用 DBCollection._find 得到查询结果。

修改查询属性


// 排序
public DBCursor sort( DBObject orderBy )
// 添加特殊设置
public DBCursor addSpecial( String name , Object o )
// hint,建议 MongoDB 使用的索引
public DBCursor hint( DBObject indexKeys )
// 快照
public DBCursor snapshot()
// 设置返回结果数量
public DBCursor limit( int n )
// 每次读取的数量
public DBCursor batchSize( int n )
// 设置开始读取的位置
public DBCursor skip( int n )
// 添加查询设置
public DBCursor addOption( int option )
// 指定查询设置
public void setOptions( int options )


  以 sort 为例:

    // 设置排序
    public DBCursor sort( DBObject orderBy ){
        // 检查是否已经执行过查询
        if ( _it != null )
            throw new IllegalStateException( "can't sort after executing query" );

        // 设置 _ordderBy,返回
        _orderBy = orderBy;
        return this;
    }


  首先,修改查询属性必须放在执行查询之前,否则将抛异常。
  其次,修改查询属性往往会修改 DBCursor 对象的属性,比如上面的代码中修改了 _orderBy 。

  修改查询属性是为执行查询做准备,执行查询时会将这些设置合并到查询对象 (_query)中。


执行查询


// Iterator 方式查询,检查是否存在下一个对象
public boolean hasNext()
// Iterator 方式查询,读取下一个对象
public DBObject next()
// Iterator 方式查询,读取当前对象
public DBObject curr()
// Array 方式查询,直接获得所有结果
public List<DBObject> toArray( int max )


  以 toArray 为例:

    // 执行查询,将结果转为 list
    public List<DBObject> toArray( int max )
        throws MongoException {

        // 检查 cursor 类型 
        _checkType( CursorType.ARRAY );

        // 执行查询,填充元素
        _fill( max );

        return _all;
    }


  执行查询前需要先通过 _checkType() 检查 cursor 类型。

  执行 hasNext()、 hasNext()、curr() 后 cursor 类型为 CursorType.ITERATOR;
  cusor 类型不为 CursorType.ARRAY 时,是不能调用 toArray 的。
  也就是说,得到 curosr 后,要么用 next() 等方式遍历结果,要么将结果直接转为 list,这两种方式是不能混用的

    // 检查 cursor 类型
    void _checkType( CursorType type ){
        if ( _cursorType == null ){
            _cursorType = type;
            return;
        }

        if ( type == _cursorType )
            return;

        throw new IllegalArgumentException( "can't switch cursor access methods" );
    }

    // 执行查询,填充元素
    void _fill( int n )
        throws MongoException {
        // 检查 cursor 类型
        _checkType( CursorType.ARRAY );

        // 循环调用 _next()
        while ( n >= _all.size() && _hasNext() )
            _next();
    }


  可以看出,Array 方式的查询,实际上是循环调用 _next(),读取所有结果。
  _next() 中又通过 _check() 来执行查询,实现如下:

   // 下一个元素
    private DBObject _next()
        throws MongoException {

        // cursor 类型为 null 时,设置为 CursorType.ITERATOR 
        // 执行 toArray() 时,这里的判断不会通过
        if ( _cursorType == null )
            _checkType( CursorType.ITERATOR );

       // 执行查询
        _check();

        _cur = null;
        _cur = _it.next();
        _num++;

        // 检查是否只读取部分字段
        if ( _keysWanted != null && _keysWanted.keySet().size() > 0 ){
            _cur.markAsPartialObject();
        }

        // 如果 cursor 类型为 CursorType.ARRAY
        // 将对象添加到结果集中
        if ( _cursorType == CursorType.ARRAY ){
            _all.add( _cur );
        }

        // 返回当前对象
        return _cur;
    }


  执行查询实际上是将之前的设置合并,构造出查询对象,然后调用 DBCollection.__find() 得到结果:

    // 执行查询
    private void _check()
        throws MongoException {
        if ( _it != null )
            return;
        
        if ( _collection != null && _query != null ){ 
            // 根据查询对象的 keySet ,自动设置 hint
            // 以便优化查询性能
            _lookForHints();

            DBObject foo = _query;
            // 特殊查询
            if ( hasSpecialQueryFields() ){
                foo = _specialFields == null ? new BasicDBObject() : _specialFields;

               // _addToQueryObject 方法调用了 query.put(key , dbObject);
               // 第三个参数表示 "dbObject" 为空对象(没有keySet)时是否执行 put 方法,缺省为 true

               // 查询条件
                _addToQueryObject( foo , "query" , _query , true );
               // 排序
                _addToQueryObject( foo , "orderby" , _orderBy , false );
               // 设置 hint
                _addToQueryObject( foo , "$hint" , _hint );

                // 执行计划
                if ( _explain )
                    foo.put( "$explain" , true );

                // 快照
                if ( _snapshot )
                    foo.put( "$snapshot", true );
            }

            // 通过 DBCollection.__find 执行查询
            _it = _collection.__find( foo, _keysWanted, _skip, _batchSize, _limit , _options );
        }

        // 结果为空
        if ( _it == null ){
            _it = (new LinkedList<DBObject>()).iterator();
            _fake = true;
        }
    }

3
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics