Java对MongoDb的CURD操作

来源:互联网 发布:js触发后台事件 编辑:程序博客网 时间:2024/05/01 22:51

最近,因为一个项目要用到MongoDB,所以简单学了下,总的来说,还是很简单的。

1. 首先是通过账号验证获取集合的代码

public static MongoCollection<Document> getCollection() {        try {            ServerAddress serverAddress = new ServerAddress("10.10.10.10", 20728);//参数为,安装了mongodb的机器ip和端口号            List<ServerAddress> addressList = new ArrayList<ServerAddress>();            addressList.add(serverAddress);            MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databasename", "password".toCharArray());            List<MongoCredential> mongoCredentialList = new ArrayList<MongoCredential>();            mongoCredentialList.add(credential);            MongoClient mongoClient = new MongoClient(addressList, mongoCredentialList);            MongoDatabase mongoDatabase = mongoClient.getDatabase("databasename");            MongoCollection<Document> collection = mongoDatabase.getCollection("collectionName");            return collection            System.out.println(collection.count());        } catch (Exception e) {            System.out.println("connect fail");        }    }

2. 向集合中插入文档

public static void insertDocument() {        try{MongoCollection<Document> collection = getCollection();Document document1 = new Document("name", "linjie").append("age", 27).append("school", "hust");  Document document2 = new Document("name", "tinting").append("age", 25).append("school", "whut"); List<Document> documents = new ArrayList<Document>(); documents.add(document1); documents.add(document2); collection.insertMany(documents); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage()); } }


3. 更新集合中的文档

  public static void updateDocument() {        try {            MongoCollection<Document> collection = getCollection();            FindIterable<Document> findIterable = collection.find(Filters.eq("name", "linjie"));            MongoCursor<Document> mongoCursor = findIterable.iterator();            Document oldDocument = mongoCursor.next();            oldDocument.put("age", 400);//修改,注意,查出来的Document中含有插入时生成的_id,此时不能修改该_id,否则插入就会失败,但是可以移除掉 oldDocument.remove("_id");            collection.updateMany(Filters.eq("name", "linjie"), new Document("$set", oldDocument));        } catch (Exception e) {            System.err.println(e);        }    }


4. 删除满足指定条件的文档

public static void deleteDocument() {        try{   MongoCollection<Document> collection = getCollection();collection.deleteMany(Filters.eq("name", "linjie")); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }


5. 查询集合中的文档

public static void findAllCollection() {        try{           MongoCollection<Document> collection = getCollection();FindIterable<Document> findIterable = collection.find();//这里find无参数是遍历集合中的所有文档,可以指定Filters.eq("name", "linjie")参数指定查询条件MongoCursor<Document> mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }


6. 创建索引

public static void createIndex() {        try{MongoCollection<Document> collection = getCollection();ListIndexesIterable<Document> documents = collection.listIndexes(); MongoCursor<Document> mongoCursor = documents.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } System.out.println("------------------"); collection.createIndex(Filters.and(new BasicDBObject("name", 1), new BasicDBObject("school", 1))); documents = collection.listIndexes(); mongoCursor = documents.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } collection.dropIndex(new BasicDBObject("name", 1)); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } }

7. Map-Ruduce思想

Map-Reduce是一种计算模型,简单的说就是将大批量的工具分解(Map)执行,然后再将结果合并成最终结果(Reduce)

使用 MapReduce 要实现两个函数 Map 函数和 Reduce 函数,Map 函数调用 emit(key, value), 遍历 collection 中所有的记录, 将key 与 value 传递给 Reduce 函数进行处理。

Map 函数必须调用 emit(key, value) 返回键值对

map函数:映射函数,将从集合中查询出的文档生成键值对序列,作为reduce函数参数(感觉这个函数应该是开了多个线程来并行执行的)

reduce函数:统计函数,reduce函数的任务就是将key-values统计成key-value,也就是把values数组统计得到一个单一的值value。

解释下如下的例子:

     map函数根据条件this.pages >= 250对文档进行转换,转换成"Big Books" -> "Understanding C++"这样的键值对

     然后应该会将map转换后的键值对进行归类,变成key-values形式,即"Big Books" -> ["Understanding C++", "Understanding Java",.....] 这样的格式

     reduce函数对每个key的values的所有值进行统计

    public static void mapReduce() {        try{            MongoCollection<Document> collection = getCollection();            Document document = new Document().append("name", "Understanding JAVA").append("pages", 100);            collection.insertOne(document);            document = new Document().append("name", "Understanding JAVA").append("pages", 100);            collection.insertOne(document);            document = new Document().append("name", "Understanding PHTHON").append("pages", 200);            collection.insertOne(document);            document = new Document().append("name", "Understanding XML").append("pages", 300);            collection.insertOne(document);            document = new Document().append("name", "Understanding MONGODB").append("pages", 400);            collection.insertOne(document);            document = new Document().append("name", "Understanding C++").append("pages", 500);            collection.insertOne(document);            document = new Document().append("name", "Understanding C#").append("pages", 500);            collection.insertOne(document);            String map = "function() { "+                    "var category; " +                    "if ( this.pages >= 250 ) "+                    "category = 'Big Books'; " +                    "else " +                    "category = 'Small Books'; "+                    "emit(category, {name: this.name});}";            String reduce = "function(key, values) { " +                    "var sum = 0; " +                    "values.forEach(function(doc) { " +                    "sum += 1; "+                    "}); " +                    "return {books: sum};} ";            MapReduceIterable<Document> documents = collection.mapReduce(map, reduce);            MongoCursor<Document> iterator = documents.iterator();            while (iterator.hasNext()) {                System.out.println(iterator.next());            }        }catch(Exception e){            System.err.println(e);        }    }



0 0
原创粉丝点击