免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3565 | 回复: 1
打印 上一主题 下一主题

[MongoDB] MongoDB Java Driver 源码分析(3):com.mongodb.DBCollection [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-11-13 17:24 |只看该作者 |倒序浏览
MongoDB Java Driver 源码分析(3):com.mongodb.DBCollection





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

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

由子类实现的方法

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  23.         return id;
  24.     }
复制代码
委托给 _db 的方法


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

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

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

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

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

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

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

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

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

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

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

论坛徽章:
0
2 [报告]
发表于 2011-11-14 09:38 |只看该作者
谢谢分享
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP