mongodb的java命令

上一篇博客已经写了mongodb 的安装和操作这一篇写一下在java环境下的使用

由于在dos 下操作mongodb 很不方便 所以我推荐大家使用mongodb 的可视化工具mongodbvue  这个是百度经验里的安装教程和使用方法    

安装:http://jingyan.baidu.com/article/ff411625b7051812e48237b8.html 

使用:http://my.oschina.net/u/1026531/blog/188336

接下来我们就步入正题在java环境下的使用mongodb

准备 :创建工程并导入mongodb 的数据库驱动jar包

mongo-2.5.3.jar 我已上传资源页(免费)

 http://download.csdn.net/detail/u012373815/9010015

首先编写数据库操作类  通过这个类基本的操作方法都已经实现,其实mongodb 的多样操作主要是看传入的BasicDBObject对象的多样化。后边我会粘贴一些BasicDBObject 的使用

publicclassMongoDBHerlper {

   privatestatic final StringHOST="127.0.0.1";

   privatestatic finalint PORT=27017;

  

   private Mongomo=null;

   public MongoDBHerlper(){

        try {

           mo=new Mongo(HOST,PORT);

          

        }catch(UnknownHostException | MongoExceptione) {

           // TODO Auto-generated catch block

           e.printStackTrace();

        } 

   }

  

   //创建链接

   publicvoid cratemongo() throws UnknownHostException,MongoException {

      mo =new Mongo();

   }

  

  

   //链接数据库并得到集合

   public DBCollectionGetDB(Stringdbname,String collname){

 

      DBdb =mo.getDB(dbname);//链接数据库

      DBCollectioncol;

      if(db.collectionExists(collname))//如果集合存在

      {

       col =db.getCollection(collname);//得到集合

      }else

      {

       col =db.createCollection(collname,null);//创建集合

      }

      returncol;

 

   }

   /**

    * 新增单条记录

    * @param dbname

    * @param collname

    * @param object

    * @return

    */

    

   publicboolean add(String dbname,String collname, BasicDBObject query){

      DBCollectioncoll=GetDB(dbname,collname);

      try {

        coll.insert(query);  

        returntrue;

       

      }catch(Exceptione) {

        // TODO: handle exception

        returnfalse;

      }finally{

        close();

      }    

   }

   /**

    * 新增多条记录

    * @param dbname数据库名

    * @param collname集合名

    * @param object传入的集合数据

    * @return

    */

   publicboolean addList(String dbname, String collname,List<DBObject> query){

      DBCollectioncoll=GetDB(dbname,collname);

      try {

        coll.insert(query);  

        returntrue;

  

      }catch(Exceptione) {

        // TODO: handle exception

        returnfalse;

      }finally{

        close();

      }    

   }

   /*

    * 查询单条

    */

   public DBObject find(Stringdbname, String collname,BasicDBObject query){

     

      DBCollectioncoll=GetDB(dbname,collname);

      try {

        DBObjectobj=coll.findOne(query);  

        returnobj;

       

      }catch(Exceptione) {

        // TODO: handle exception

        System.out.println("查询出错了");

        returnnull;

      }finally{

        close();

      }    

   } 

   /*

    * 查询多条

    */

   public List<DBObject>findList(Stringdbname,String collname,BasicDBObjectquery){

     

      DBCollectioncoll=GetDB(dbname,collname);

      try {

        List<DBObject>obj=coll.find(query).toArray();   

        returnobj;

       

      }catch(Exceptione) {

        // TODO: handle exception

        System.out.println("查询出错了");

        returnnull;

      }finally{

        close();

      }    

   }

   /*

    * 更新单条

    */

   publicboolean update(String dbname, String collname, BasicDBObject query,BasicDBObject o){

     

      DBCollectioncoll=GetDB(dbname,collname);

      try {

        coll.update(query, o);

        returntrue;

       

      }catch(Exceptione) {

        // TODO: handle exception

        System.out.println("更新出错了");

        returnfalse;

      }finally{

        close();

      }    

   }

  

  

  

   /*

    * 删除单条

    */

   publicboolean delete(String dbname, String collname, BasicDBObject query){

     

      DBCollectioncoll=GetDB(dbname,collname);

      try {

        coll.remove(query);

        returntrue;

       

      }catch(Exceptione) {

        // TODO: handle exception

        System.out.println("删除出错了");

        returnfalse;

      }finally{

        close();

      } 

   }

   //关闭连接

   publicvoid close(){

      this.mo.close();

   } 

}

BasicDBObject 的案例  (由于当时写的时候没有保存案列这个就找了一个和我当初学的差不多的案例粘贴了出来共同学习)

publicclass MongoDB4CRUDTest {

   

    private Mongo mg = null;

    private DB db;

    private DBCollection users;

   

    @Before

    publicvoid init() {

        try {

            mg = new Mongo();

            //mg = new Mongo("localhost",27017);

        } catch (UnknownHostException e) {

            e.printStackTrace();

        } catch (MongoException e) {

            e.printStackTrace();

        }

        //获取temp DB;如果默认没有创建,mongodb会自动创建

        db = mg.getDB("temp");

        //获取users DBCollection;如果默认没有创建,mongodb会自动创建

        users = db.getCollection("users");

    }

   

    @After

    publicvoid destory() {

        if (mg != null)

            mg.close();

        mg = null;

        db = null;

        users = null;

        System.gc();

    }

   

    publicvoid print(Object o) {

        System.out.println(o);

    }

}

 

3添加操作

在添加操作之前,我们需要写个查询方法,来查询所有的数据。代码如下:

/**

 * <b>function:</b>查询所有数据

 * @author hoojo

 * @createDate 2011-6-2下午03:22:40

 */

privatevoid queryAll() {

    print("查询users的所有数据:");

    //db游标

    DBCursor cur = users.find();

    while (cur.hasNext()) {

        print(cur.next());

    }

}

 

@Test

publicvoid add() {

    //先查询所有数据

    queryAll();

    print("count: " + users.count());

   

    DBObject user = new BasicDBObject();

    user.put("name","hoojo");

    user.put("age", 24);

    //users.save(user)保存,getN()获取影响行数

    //print(users.save(user).getN());

   

    //扩展字段,随意添加字段,不影响现有数据

    user.put("sex","");

    print(users.save(user).getN());

   

    //添加多条数据,传递Array对象

    print(users.insert(user, new BasicDBObject("name", "tom")).getN());

   

    //添加List集合

    List<DBObject> list = new ArrayList<DBObject>();

    list.add(user);

    DBObject user2 = new BasicDBObject("name", "lucy");

    user.put("age", 22);

    list.add(user2);

    //添加List集合

    print(users.insert(list).getN());

   

    //查询下数据,看看是否添加成功

    print("count: " + users.count());

    queryAll();

}

 

4删除数据

@Test

publicvoid remove() {

    queryAll();

    print("删除id = 4de73f7acd812d61b4626a77" + users.remove(new BasicDBObject("_id",new ObjectId("4de73f7acd812d61b4626a77"))).getN());

    print("remove age >= 24: " + users.remove(new BasicDBObject("age",new BasicDBObject("$gte", 24))).getN());

}

 

5修改数据

@Test

publicvoid modify() {

    print("修改:" + users.update(new BasicDBObject("_id",new ObjectId("4dde25d06be7c53ffbd70906")),new BasicDBObject("age", 99)).getN());

    print("修改:" + users.update(

            new BasicDBObject("_id", new ObjectId("4dde2b06feb038463ff09042")),

            new BasicDBObject("age", 121),

            true,//如果数据库不存在,是否添加

            false//多条修改

            ).getN());

    print("修改:" + users.update(

            new BasicDBObject("name", "haha"),

            new BasicDBObject("name", "dingding"),

            true,//如果数据库不存在,是否添加

            true//false只修改第一天,true如果有多条就不修改

            ).getN());

   

    //当数据库不存在就不修改、不添加数据,当多条数据就不修改

    //print("修改多条:" + coll.updateMulti(newBasicDBObject("_id", newObjectId("4dde23616be7c19df07db42c")), newBasicDBObject("name", "199")));

}

 

6查询数据

@Test

publicvoid query() {

    //查询所有

    //queryAll();

   

    //查询id = 4de73f7acd812d61b4626a77

    print("find id = 4de73f7acd812d61b4626a77:" + users.find(new BasicDBObject("_id",new ObjectId("4de73f7acd812d61b4626a77"))).toArray());

   

    //查询age = 24

    print("find age = 24: " + users.find(new BasicDBObject("age", 24)).toArray());

   

    //查询age >= 24

    print("find age >= 24: " + users.find(new BasicDBObject("age",new BasicDBObject("$gte", 24))).toArray());

    print("find age <= 24: " + users.find(new BasicDBObject("age",new BasicDBObject("$lte", 24))).toArray());

   

    print("查询age!=25" + users.find(new BasicDBObject("age", new BasicDBObject("$ne", 25))).toArray());

    print("查询age in 25/26/27" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.IN, new int[] { 25, 26, 27}))).toArray());

    print("查询age not in 25/26/27" + users.find(new BasicDBObject("age",new BasicDBObject(QueryOperators.NIN, new int[] { 25, 26, 27}))).toArray());

    print("查询age exists排序:" + users.find(new BasicDBObject("age",newBasicDBObject(QueryOperators.EXISTS, true))).toArray());

   

    print("只查询age属性:" + users.find(null,new BasicDBObject("age", true)).toArray());

    print("只查属性:" + users.find(null,new BasicDBObject("age", true), 0, 2).toArray());

    print("只查属性:" + users.find(null,new BasicDBObject("age", true), 0, 2, Bytes.QUERYOPTION_NOTIMEOUT).toArray());

   

    //只查询一条数据,多条去第一条

    print("findOne: " + users.findOne());

    print("findOne: " + users.findOne(new BasicDBObject("age", 26)));

    print("findOne: " + users.findOne(new BasicDBObject("age", 26),new BasicDBObject("name", true)));

   

    //查询修改、删除

    print("findAndRemove查询age=25的数据,并且删除: " + users.findAndRemove(new BasicDBObject("age", 25)));

   

    //查询age=26的数据,并且修改name的值为Abc

    print("findAndModify: " + users.findAndModify(new BasicDBObject("age", 26),new BasicDBObject("name","Abc")));

    print("findAndModify: " + users.findAndModify(

        new BasicDBObject("age", 28),//查询age=28的数据

        new BasicDBObject("name", true),//查询name属性

        new BasicDBObject("age", true),//按照age排序

        false, //是否删除,true表示删除

        new BasicDBObject("name","Abc"), //修改的值,将name修改成Abc

        true,

        true));

   

    queryAll();

}

mongoDB不支持联合查询、子查询,这需要我们自己在程序中完成。将查询的结果集在Java查询中进行需要的过滤即可。

 

7其他操作

publicvoid testOthers() {

    DBObject user = new BasicDBObject();

    user.put("name","hoojo");

    user.put("age", 24);

   

    //JSON对象转换       

    print("serialize: " + JSON.serialize(user));

    //反序列化

    print("parse: " + JSON.parse("{ \"name\" :\"hoojo\" , \"age\" : 24}"));

   

    print("判断temp Collection是否存在: " + db.collectionExists("temp"));

   

    //如果不存在就创建

    if (!db.collectionExists("temp")) {

        DBObject options = new BasicDBObject();

        options.put("size", 20);

        options.put("capped", 20);

        options.put("max", 20);                                

        print(db.createCollection("account", options));

    }

   

    //设置db为只读

    db.setReadOnly(true);

   

    //只读不能写入数据

   db.getCollection("test").save(user);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值