首页 > 代码库 > mongodb--java操作

mongodb--java操作

一、mongodb客户端

   mongodb提供诸多语言的客户端,也包括java的客户端。通过这些客户端,我们可以很方便地使用编写代码的方式对mongodb进行操作。这里使用java客户端进行示例。使用java客户端首先需要下载jmongodb数据库java驱动。驱动的源码地址为:https://github.com/mongodb/mongo-java-driver/ 。这里工程使用maven构建,需要添加的依赖如下:

<dependency>  <groupId>org.mongodb</groupId>  <artifactId>mongo-java-driver</artifactId>  <version>2.12.4</version></dependency>

二、示例

   1、添加文档

DB db = null;    @Before    public void getDb() throws UnknownHostException {        MongoClient mongoClient = new MongoClient();        // mongoClient = new MongoClient("localhost");        // mongoClient = new MongoClient( "localhost" , 27017 );        // mongoClient = new MongoClient(Arrays.asList(new  ServerAddress("localhost", 27017), new ServerAddress("localhost", 27018), new ServerAddress("localhost", 27019)));        //需要验证的如下         // MongoCredential credential =  MongoCredential.createMongoCRCredential(userName, database, password);        // MongoClient mongoClient = new MongoClient(new ServerAddress(),  Arrays.asList(credential));        mongoClient.setWriteConcern(WriteConcern.JOURNALED);        System.out.println("===========DatabaseName=============");        for (String s : mongoClient.getDatabaseNames()) {            System.out.println(s);        }        db = mongoClient.getDB("testdb");    }    @Test    public void addDoc() {        DBCollection coll = db.getCollection("person");        BasicDBObject doc = new BasicDBObject("name", "张三")//                .append("age", 20)//                .append("gender", "mail")//                .append("brithday", new Date())                //                .append("info",                        new BasicDBObject("location_x", 203).append(                                "location_y", 303));        WriteResult result = coll.insert(doc);        System.out.println(result);        for (int i = 0; i < 10; i++) {            BasicDBObject document = new BasicDBObject("name", "zhangsan" + i)//                    .append("age", 18 + i)//                    .append("brithday", new Date());            WriteResult result2 = coll.insert(document);            System.out.println(result2);        }    }

  2、查询文档

    @Test    public void findDoc() {        DBCollection coll = db.getCollection("person");        DBObject person = coll.findOne();// 获取集合中的第一个文档        System.out.println("===============findOne======================");        System.out.println(person);        // 根据条件查询;db.person.find({age:18});        DBObject query = new BasicDBObject("age", 18);        DBObject person2 = coll.findOne(query);        System.out.println(person2);        System.out                .println("===============findByCondtion======================");        // age小于25; db.person.find({age:{$lt:25}});        query = new BasicDBObject("age", new BasicDBObject("$lt", 25));        DBCursor cursor = coll.find(query);        try {            while (cursor.hasNext()) {                System.out.println(cursor.next());            }        } finally {            cursor.close();        }        System.out.println("===============findAll======================");        // 查询所有并按照age升序;db.person.find().sort({age:1});        cursor = coll.find().sort(new BasicDBObject("age", -1));// 1升序,-1降序        try {            while (cursor.hasNext()) {                System.out.println(cursor.next());            }        } finally {            cursor.close();        }    }

  3、更新文档

       @Test    public void updateDoc() {        DBCollection coll = db.getCollection("person");        BasicDBObject query = new BasicDBObject("name", "张三");        DBObject update = coll.findOne(query);        update.put("info", new BasicDBObject("location_x", 1999).append(                "location_y", 2999));        // 方法一        DBObject person = coll.findAndModify(query, update);// 返回的是未更改前的文档对象        System.out.println(person);        // 方法二        update.put("info", new BasicDBObject("location_x", 19998).append(                "location_y", 29998));        WriteResult result = coll.update(query, update);        System.out.println(result);    }    

  4、删除文档

       @Test    public void deleteDoc() {        DBCollection coll = db.getCollection("person");        BasicDBObject query = new BasicDBObject("name", "zhangsan8");        // 方法一        query = new BasicDBObject("name", "zhangsan9");        DBObject person = coll.findAndRemove(query);// 返回的是删除的文档对象        System.out.println(person);        // 方法二        query = new BasicDBObject("name", "zhangsan9");        WriteResult result = coll.remove(query);        System.out.println(result);    } 

  5、集合相关操作

       @Test    public void testCollection() {        Set<String> colls = db.getCollectionNames();// 数据库中的所有集合name        for (String s : colls) {            System.out.println(s);        }        System.out.println("=======================================");        // 创建一个collection,并在collection中添加document        DBCollection coll = db.createCollection("testCollection",                new BasicDBObject("capped", true).append("size", 1048576));        System.out.println(coll);        coll = db.getCollection("testCollection");        // collection中的索引        List<DBObject> list = coll.getIndexInfo();        for (DBObject o : list) {            System.out.println(o);        }        coll.drop();    }    

mongodb--java操作