zoukankan      html  css  js  c++  java
  • Mongo中append方法使用

    在MongoDB的官网已经很详细的介绍了各种客户端的使用,其中也包括java的,在此,仅对几个比较疑惑的地方做个标注:

    (1)、如何向db中添加collection?

    如果在api文档中找不到答案,那就去看源代码吧。可以看到com.mongodb.DB类中是如何定义getCollection方法的。其中DB类是抽象类,且doGetCollection(name)方法也是抽象的。

    Java代码  收藏代码
    1. /** 
    2.      * <strong>Gets a collection with a given name.</strong> 
    3.      * I<strong>f the collection does not exist, a new collection is created</strong>. 
    4.      * @param name the name of the collection to return 
    5.      * @return the collection 
    6.      */  
    7.     public final DBCollection getCollection( String name ){  
    8.         DBCollection c = doGetCollection( name );  
    9.         return c;  
    10.     }  

    可见,当调用db.getCollection( String name )方法时,如果以name命名的collection不存在,则自动创建一个,并返回。

    (2)、BasicDBObject的append和put两个方法有何区别?

    首先看一下BasicDBObject的继承结构,com.mongodb.BasicDBObject --》com.mongodb.DBObject(接口)  --》org.bson.BSONObject(接口)。

    其中,put( String key , Object v )方法是BSONObject接口定义的,具体定义如下:

    Java代码  收藏代码
    1. public interface BSONObject {  
    2.     /** 
    3.      * Sets a name/value pair in this object. 
    4.      * @param key Name to set 
    5.      * <strong>@param v Corresponding value</strong> 
    6.      * <strong>@return <tt>v</tt></strong> 
    7.      */  
    8.     public Object put( String key , Object v );  
    9. }  

     而append( String key , Object val )方法的定义是在BasicDBObject类中,具体定义如下:

    Java代码  收藏代码
    1. public class BasicDBObject extends BasicBSONObject implements DBObject {  
    2.     @Override  
    3.     public BasicDBObject append( String key , Object val ){  
    4.         put( key , val );  
    5.         <strong>return this;</strong>  
    6.     }  
    7. }  

     可以看出,put方法返回的是value值,而append方法返回的是对象本身,这样就可以向使用链式的方式添加数据,如:new BasicDBObject().append("username","zhang").append("password","111111");

  • 相关阅读:
    Springboot配置文件解析器
    ThreadLocal的简单使用和实现原理
    hashCode()方法对HashMap的性能影响
    Thread中的join()方法
    Windows使用MongoDB,以及索引创建
    Android--我的Butterknife黄油刀怎么找不到控件了!!!
    Android--RecyclerView的封装使用
    Android--自定义加载框
    Android--Retrofit+RxJava的简单封装(三)
    Android--Retrofit+RxJava(二)
  • 原文地址:https://www.cnblogs.com/Wen-yu-jing/p/3533734.html
Copyright © 2011-2022 走看看