Mongodb系列- java客户端简单使用(CRUD)

2018-06-18 02:13:59来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

Mongodb提供了很多的客户端: shell,python, java, node.js...等等.

以 java 为例实现简单的增删改查

pom文件:

 

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.4.3</version>
    </dependency>
     <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver-async</artifactId>
        <version>3.4.3</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.25</version>
    </dependency>
  </dependencies>

 

在这里我们先封装一个mongodb管理类:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.result.DeleteResult;
/**
 * MongoDB管理类
 * @author jiangyuechao
 *
 */
public class MongoDBHelper {
    static Logger logger = LoggerFactory.getLogger(MongoDBHelper.class);

    static String ip = "10.80.18.1";
    //10.80.21.41 10.80.18.1
    static MongoClient mongoClient = new MongoClient(ip, 27017);
    //MongoDatabase实例是不可变的
    static MongoDatabase database;
    //firstDB
    public static void connect(String databaseName){
        database = mongoClient.getDatabase(databaseName);
    }
    
    public static MongoCollection<Document> getCollection(String collectionName){
        //MongoCollection实例是不可变的
        if(!collectionExists(collectionName)){
            return null;
        }
        MongoCollection<Document> collection = database.getCollection(collectionName);
        return collection;
    }
    
    public static boolean collectionExists(final String collectionName) {
         boolean collectionExists = database.listCollectionNames()
                .into(new ArrayList<String>()).contains(collectionName);
        return collectionExists;
        /*MongoIterable<String> mongoIterable = database.listCollectionNames();
        for (Iterator<String> iterator = mongoIterable.iterator(); iterator.hasNext();) {
            String name = iterator.next();
            logger.info("name:{}", name);
            if(name.equals(collectionName)){
                return true;
            }
        }
        return false;*/
    }
    
    public static void getAllDocuments(MongoCollection<Document> collection){
        MongoCursor<Document> cursor = collection.find().iterator();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }
    }
    
    public static String getDocumentFirst(MongoCollection<Document> collection){
        Document myDoc = collection.find().first();
        return myDoc.toJson();
    }
    
    public static void createDocument(MongoCollection<Document> collection,Map<String,Object> map){
        System.out.println("--------------------");
        map.forEach((k,v)->{ System.out.println("Key : " + k + " Value : " + v);});
    }
    /**
     * 插入一个Document
     * @param collection
     * @param doc
     */
    public static void insertDocument(MongoCollection<Document> collection,Document doc){
        collection.insertOne(doc);
    }
    /**
     * 插入多个Document
     * @param collection
     * @param documents
     */
    public static void insertManyDocument(MongoCollection<Document> collection,List<Document> documents){
        collection.insertMany(documents);
    }
    /**
     * 显示创建集合
     */
    public static void explicitlyCreateCollection(String collectionName){
        database.createCollection(collectionName,
                new CreateCollectionOptions().capped(false));
    }

    // 删除集合的所有文档
    public static long deleteAllDocument(MongoCollection<Document> collection) {
        DeleteResult deleteResult = collection.deleteMany(new Document());
        long count = deleteResult.getDeletedCount();
        return count;
    }

    // 删除集合
    public static void deleteCollection(MongoCollection<Document> collection) {
        collection.drop();
    }

    /**
     * <p>
     * 关闭客户端
     * </p>
     * 
     * @author jiangyuechao 2018年4月9日 上午11:23:36
     */
    public static void closeDb() {
        mongoClient.close();
    }
}

简单分析:

1. 使用 ip, port 连接mongodb数据库: static MongoClient mongoClient = new MongoClient(ip, 27017);

2. 连接数据库: database = mongoClient.getDatabase(databaseName);

3. 连接集合: MongoCollection<Document> collection = database.getCollection(collectionName);

4. 封装了基本的创建集合, insert ,delete操作.

使用实例

QuickTour例子:

package com.chaochao.mongodb;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.gte;
import static com.mongodb.client.model.Filters.lt;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.bson.Document;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;

public class QuickTour {
    static String databaseName = "firstDB";
    static String collectionName = "firstCollection1";
    static MongoCollection<Document> firstCollection;
    
    public static void main(String[] args) {
        QuickTour  quickTour = new QuickTour();
        quickTour.setUp();
//        quickTour.updateMultipleDoc();
//        quickTour.deleteMultiple();
        quickTour.getAllDocuments();
    }
    
    /**
     * 连接数据库
     */
    public void setUp(){
        MongoDBHelper.connect(databaseName);
        firstCollection =  MongoDBHelper.getCollection(collectionName);
    }
    public void getAllDocuments(){
        MongoDBHelper.getAllDocuments(firstCollection);
    }
    
    public void getDocumentFirst(){
        MongoDBHelper.connect(databaseName);
        MongoCollection<Document> collection = MongoDBHelper.getCollection(collectionName);
        String json = MongoDBHelper.getDocumentFirst(collection);
        System.out.println(json);
    }
    
    /**
     * 返回符合匹配条件的第一个doc
     * @param collection
     */
    public void getDocMatcheFilter(){
        Document myDoc = firstCollection.find(eq("y", 2)).first();
        System.out.println(myDoc.toJson());
    }
    
    public void getAllDocMatcheFilter(){
        firstCollection.find(Filters.gt("i", 10)).forEach((Document document)->{System.out.println(document.toJson());});
    }
    
    public void updateOneDoc(){
        UpdateResult updateResult = firstCollection.updateOne(Filters.eq("i", 12), new Document("$set", new Document("i", 21)));
        System.out.println(updateResult.getModifiedCount());
    }
    public void updateMultipleDoc(){
        UpdateResult updateResult = firstCollection.updateMany(lt("i", 100), new Document("$inc", new Document("i", 100)));
        System.out.printf("count:%s,insertedId:%s",updateResult.getModifiedCount(),updateResult.getUpsertedId());
        System.out.println();
    }
    
    public void deleteOne(){
        DeleteResult deleteResult = firstCollection.deleteOne(eq("i", 121));
        System.out.println(deleteResult.getDeletedCount());
    }
    public void deleteMultiple(){
        DeleteResult deleteResult = firstCollection.deleteMany(gte("i", 100));
        System.out.println(deleteResult.getDeletedCount());
    }
    
    /**
     * 插入一个doc
     * @param collection
     */
    public void insertDocument(){
        Document doc = new Document("name", "MongoDB")
                    .append("type", "database")
                    .append("count", 1)
                    .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
                    .append("info", new Document("x", 203).append("y", 102));
        MongoDBHelper.insertDocument(firstCollection, doc);
    }
    /**
     * 插入多个doc
     * @param collection
     */
    public void insertMultipleDoc(){
        List<Document> documents = new ArrayList<Document>();
        for (int i = 0; i < 100; i++) {
            documents.add(new Document("i", i));
        }

        MongoDBHelper.insertManyDocument(firstCollection, documents);
    }
    
    public void countDocs(){
        System.out.println(firstCollection.getNamespace().getCollectionName()+"-count:"+firstCollection.count());
    }
    
}

这个例子展示了基本的增删改查操作,直接可以运行..安装mongodb参照官网,挺简单的,java 连接mongodb参照我前边的博客: Java驱动远程连接mongoDB(简明易懂版)

 

比如我的获取firstCollection1 集合的所有文档 :

{ "_id" : { "$oid" : "5a631d80070db90c43a3477d" }, "x" : 1.0 }
{ "_id" : { "$oid" : "5a631db0070db90c43a3477e" }, "y" : 2.0 }
{ "_id" : 10.0, "calc" : 2.555555000005E12 }
{ "_id" : { "$oid" : "5a66d717ba3c702c14df31b3" }, "name" : "MongoDB", "type" : "database", "count" : 1, "versions" : ["v3.2", "v3.0", "v2.6"], "info" : { "x" : 203, "y" : 102 } }
{ "_id" : { "$oid" : "5a9220cafffeed155066c035" }, "domainID" : { "$numberLong" : "2001" }, "type" : "chao" }

 

mongodb简单的CRUD还是很好理解的,这里只是一个入门,让你快速熟悉它的操作,跟传统的数据库逻辑还是一致的:

1. 连接数据库

2. 执行操作

3. 关闭连接

 

那些复杂的查询和更新操作,我们放在后边介绍,比如: 如何匹配数组中的元素? 如何匹配嵌入文档,查询值为 null 的字段 等等..

转载注明出处: http://www.cnblogs.com/jycboy/p/8758754.html

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:1045-access denied for user &#39;root&#39;@

下一篇:分布式全局ID生成器(雪花算法)