凝望长空 发表于 2011-11-13 17:24

MongoDB Java Driver 源码分析(3):com.mongodb.DBCollection

MongoDB Java Driver 源码分析(3):com.mongodb.DBCollection




DBCollection 是表示数据集合的抽象类,它的实现可以简单地分为两类:
  一类是抽象方法,由子类(DBApiLayer.MyCollection)实现;
  另一类委托给类型为 "DB" 的属性 _db,_db 实际上是 DBApiLayer 类的实例(DBApiLayer 继承抽象类 DB);

  因此,DBCollection 类是实现细节与 DBApiLayer 关系密切。
  DBApiLyer 的实现细节我们将在后续文章中进行详细的描述,本文主要探讨两者之间的联系。

由子类实现的方法

  以下方法是由子类实现的,这些将在介绍 DBApiLayer 时再进行详细说明:

Java代码1.// 插入记录   
2.public abstract WriteResult insert(DBObject[] arr , WriteConcern concern )   
3.
4.// 更新记录   
5.public abstract WriteResult update( DBObject q , DBObject o , boolean upsert , boolean multi , WriteConcern concern )   
6.
7.// 保存数据之前附加额外属性   
8.protected abstract void doapply( DBObject o )   
9.
10.// 删除记录   
11.public abstract WriteResult remove( DBObject o , WriteConcern concern )   
12.
13.// 查询记录   
14.abstract Iterator<DBObject> __find( DBObject ref , DBObject fields , int numToSkip , int batchSize , int limit, int options )   
15.
16.// 创建索引   
17.public abstract void createIndex( DBObject keys , DBObject options )   
// 插入记录
public abstract WriteResult insert(DBObject[] arr , WriteConcern concern )

// 更新记录
public abstract WriteResult update( DBObject q , DBObject o , boolean upsert , boolean multi , WriteConcern concern )

// 保存数据之前附加额外属性
protected abstract void doapply( DBObject o )

// 删除记录
public abstract WriteResult remove( DBObject o , WriteConcern concern )

// 查询记录
abstract Iterator<DBObject> __find( DBObject ref , DBObject fields , int numToSkip , int batchSize , int limit, int options )

// 创建索引
public abstract void createIndex( DBObject keys , DBObject options )   此外,以下方法是在这些方法的基础上,在进行包装和组合得到的:

Java代码1.public final void ensureIndex( final DBObject keys , final DBObject optionsIN )   
2.public final DBObject findOne( DBObject o, DBObject fields )   
3.public final Object apply( DBObject jo , boolean ensureID )
public final void ensureIndex( final DBObject keys , final DBObject optionsIN )
public final DBObject findOne( DBObject o, DBObject fields )
public final Object apply( DBObject jo , boolean ensureID )  ensurceIndex 方法用于创建索引,调用了抽象方法 createdIndex ,在此之前,先检查数据库是否为只读,以及是否重复创建索引。
  具体实现如下:

Java代码1.public final void ensureIndex( final DBObject keys , final DBObject optionsIN )   
2.    throws MongoException {   
3.
4.    // 检查是否为只读   
5.    if ( checkReadOnly( false ) ) return;   
6.
7.    // 设置参数   
8.    final DBObject options = defaultOptions( keys );   
9.    for ( String k : optionsIN.keySet() )   
10.      options.put( k , optionsIN.get( k ) );   
11.
12.    // 取得参数中的索引名称   
13.    final String name = options.get( "name" ).toString();   
14.
15.    // 如果索引已经创建,则返回,避免重复创建   
16.    if ( _createdIndexes.contains( name ) )   
17.      return;   
18.
19.    // 创建索引,并添加到 createdIndexes   
20.    createIndex( keys , options );   
21.    _createdIndexes.add( name );   
22.}
    public final void ensureIndex( final DBObject keys , final DBObject optionsIN )
      throws MongoException {

      // 检查是否为只读
      if ( checkReadOnly( false ) ) return;

      // 设置参数
      final DBObject options = defaultOptions( keys );
      for ( String k : optionsIN.keySet() )
            options.put( k , optionsIN.get( k ) );

      // 取得参数中的索引名称
      final String name = options.get( "name" ).toString();

      // 如果索引已经创建,则返回,避免重复创建
      if ( _createdIndexes.contains( name ) )
            return;

      // 创建索引,并添加到 createdIndexes
      createIndex( keys , options );
      _createdIndexes.add( name );
    }  findOne 方法用于查询一个对象,第一个参数是表示查询条件的 DBObject,第二个参数表示返回结果包含的字段。
  调用了抽象方法 _find,并取第一条。
  具体实现如下:

Java代码1.public final DBObject findOne( DBObject o, DBObject fields ) {   
2.    // 调用 _find 方法   
3.    Iterator<DBObject> i = __find( o , fields , 0 , -1 , 0, getOptions() );   
4.
5.    // 读取第一条记录   
6.    if ( i == null || ! i.hasNext() )   
7.      return null;   
8.    return i.next();   
9.}
    public final DBObject findOne( DBObject o, DBObject fields ) {
      // 调用 _find 方法
      Iterator<DBObject> i = __find( o , fields , 0 , -1 , 0, getOptions() );

      // 读取第一条记录
      if ( i == null || ! i.hasNext() )
            return null;
      return i.next();
    }  apply 方法用于在保存对象之前,为对象添加额外的属性。
  除了调用抽象方法 doapply,还可以根据 ensureId 的值,生成 id。
  具体实现如下:

Java代码1.public final Object apply( DBObject jo , boolean ensureID ){   
2.    // 根据 ensureId 的值,确定是否生成 id   
3.    Object id = jo.get( "_id" );   
4.    if ( ensureID && id == null ){   
5.      id = ObjectId.get();   
6.      jo.put( "_id" , id );   
7.    }   
8.
9.    // 调用抽象方法 doapply,为对象附加额外属性。   
10.    doapply( jo );   
11.
12.    return id;   
13.}
    public final Object apply( DBObject jo , boolean ensureID ){
      // 根据 ensureId 的值,确定是否生成 id
      Object id = jo.get( "_id" );
      if ( ensureID && id == null ){
            id = ObjectId.get();
            jo.put( "_id" , id );
      }

      // 调用抽象方法 doapply,为对象附加额外属性。
      doapply( jo );

      return id;
    }委托给 _db 的方法


Java代码1.// 查询并修改对象   
2.public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort,   
3.    boolean remove, DBObject update, boolean returnNew, boolean upsert)   
4.
5.// 删除索引   
6.public void dropIndexes( String name )   
7.
8.// 删除该数据集   
9.public void drop()   
10.
11.// 统计数量   
12.public long getCount(DBObject query, DBObject fields, long limit, long skip )   
13.
14.// 重命名该集合   
15.public DBCollection rename( String newName, boolean dropTarget )   
16.
17.// 执行 Group 操作   
18.public DBObject group( GroupCommand cmd )   
19.
20.// 查询对象并去除重复   
21.public List distinct( String key , DBObject query )   
22.
23.// 执行 Map Reduce 操作   
24.public MapReduceOutput mapReduce( MapReduceCommand command )   
25.
26.// 获取索引信息   
27.public List<DBObject> getIndexInfo()   
28.
29.// 获取子数据集   
30.public DBCollection getCollection( String n )
// 查询并修改对象
public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort,
    boolean remove, DBObject update, boolean returnNew, boolean upsert)

// 删除索引
public void dropIndexes( String name )

// 删除该数据集
public void drop()

// 统计数量
public long getCount(DBObject query, DBObject fields, long limit, long skip )

// 重命名该集合
public DBCollection rename( String newName, boolean dropTarget )

// 执行 Group 操作
public DBObject group( GroupCommand cmd )

// 查询对象并去除重复
public List distinct( String key , DBObject query )

// 执行 Map Reduce 操作
public MapReduceOutput mapReduce( MapReduceCommand command )

// 获取索引信息
public List<DBObject> getIndexInfo()

// 获取子数据集
public DBCollection getCollection( String n )  以 findAndModify 为例。
  findAndModify 方法用于查询并修改对象,实际调用的是 _db.command( cmd ) 方法;
  在调用 _db 的方法之前,先对 cmd 进行组装,添加查询条件、查询字段、排序条件等;
  然后调用 _db.command( cmd ),返回结果或抛出异常。
  具体实现如下:

Java代码1.public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort,   
2.    boolean remove, DBObject update, boolean returnNew, boolean upsert) {   
3.    // 创建 cmd 对象   
4.    BasicDBObject cmd = new BasicDBObject( "findandmodify", _name);   
5.
6.    // 添加查询条件   
7.    if (query != null && !query.keySet().isEmpty())   
8.      cmd.append( "query", query );   
9.
10.    // 添加查询字段   
11.    if (fields != null && !fields.keySet().isEmpty())   
12.      cmd.append( "fields", fields );   
13.
14.    // 添加排序字段   
15.    if (sort != null && !sort.keySet().isEmpty())   
16.      cmd.append( "sort", sort );   
17.
18.    // 是否执行删除   
19.    if (remove)   
20.      cmd.append( "remove", remove );   
21.    else {   
22.      // 添加更新的字段   
23.      if (update != null && !update.keySet().isEmpty()) {   
24.            // if 1st key doesnt start with $, then object will be inserted as is, need to check it   
25.            String key = update.keySet().iterator().next();   
26.            if (key.charAt(0) != '$')   
27.                _checkObject(update, false, false);   
28.            cmd.append( "update", update );   
29.      }   
30.      // 是否返回新创建的对象   
31.      if (returnNew)   
32.            cmd.append( "new", returnNew );   
33.
34.       // 被查询的对象不存在时是否创建一个   
35.       if (upsert)   
36.            cmd.append( "upsert", upsert );   
37.    }   
38.
39.    // 删除操作与更新操作不能混合,抛异常   
40.    if (remove && !(update == null || update.keySet().isEmpty() || returnNew))   
41.      throw new MongoException("FindAndModify: Remove cannot be mixed with the Update, or returnNew params!");   
42.
43.    // 执行 _db.command( cmd )   
44.    CommandResult res = this._db.command( cmd );   
45.
46.    // 返回结果或抛异常   
47.    if (res.ok() || res.getErrorMessage().equals( "No matching object found" ))   
48.      return (DBObject) res.get( "value" );   
49.    res.throwOnError();   
50.    return null;   
51.}

寂寞冲咖啡 发表于 2011-11-14 09:38

谢谢分享
页: [1]
查看完整版本: MongoDB Java Driver 源码分析(3):com.mongodb.DBCollection