MongoDB安裝與測試

MongoDB安裝與測試

1.下載MongoDB,選定windows版本
MongoDB下載地址
JDBC下載地址
2.安裝
2.1 運行“mongodb-win32-x86_64-2008plus-ssl-3.4.5-signed.msi”安裝MongoDB。
2.2 安裝完成後,進入安裝目錄下的bin目錄,建立批處理文件mongod.bat,內容如下(其中“d:\dbpart\MongoDB\db”爲數據目錄,可根據實際情況自行更改):

mongod.exe --dbpath=d:\dbpart\MongoDB\db --directoryperdb  --logpath d:\dbpart\MongoDB\logs.txt --logappend

說明:日誌文件爲d:\dbpart\MongoDB\logs.txt,以及添加方式記錄(追加–logappend)。
數據目錄爲d:\dbpart\MongoDB\db,並且每個數據庫將儲存在一個單獨的目錄(–directoryperdb)。
2.3 然後建立數據庫目錄“d:\dbpart\MongoDB\db”,CMD進入安裝目錄下的bin目錄,執行批命令:mongod.bat(當然也可以將上述命令自己敲一遍)。如下圖所示:
這裏寫圖片描述
2.4 這時,在我們建立的數據庫目錄“d:\dbpart\MongoDB\db”中可以看到出現了許多文件夾及文件,如下圖所示:
這裏寫圖片描述
2.5 測試時,服務器端要一直運行。

3.客戶端
3.1啓動客戶端
再打開一個CMD窗口,執行安裝目錄下的bin目錄中的mongo.exe,如下圖所示:
這裏寫圖片描述
說明
shell會在啓動時自動連接MongoDB服務器,默認連接test數據庫,並將這個數據庫連接賦值給全局變量db,這個變量是MongoDB的主要入口點。shell是功能完備的JavaScript解釋器,可以運行任何javascript程序。
MongoDB使用GridFS來儲存大文件。每個BSON對象大小不能超過4MB。
字段名限制:不能以“$”開頭;不能包含“.”;“_id”是系統保留的字段,但用戶可以自己儲存唯一性的數據在字段中。
MongoDB爲每個數據庫分配一系列文件。每個數據文件都會被預分配一個大小,第一個文件名字爲“.0”,大小爲64MB,第二個文件“.1”爲128MB,依此類推,文件大小上限爲2GB。如下:

3.2查詢系統數據庫
show dbs // 列出所有數據庫
admin:從權限角度來看,這是‘root’數據庫.要是將一個用戶添加到這個數據庫,這個用戶自動繼承所有數據庫的權限。有些服務器命令也只能從這個數據庫運行,如關閉服務器
local:這個數據庫永遠不會被複制,可以用來存儲於本地單臺服務器的任意集合
這裏寫圖片描述
3.2新建數據庫
use person // 使用數據庫person。即使這個數據庫不存在也可以執行,但該數據庫不會立刻被新建,要等到執行了insert等的操作時,纔會建立這個數據庫。但是直接離開的話,這個數據庫會被mongo刪除。
3.3 插入數據
db.person.insert({name:”zhang_3”,age:20,address:”xi_an”});
db.person.insert({name:”li_4”,age:30,address:”si_chuan”});
db.person.insert({name:”wang_2”,age:40,address:”tai_wan”});
這裏寫圖片描述
3.4 查詢數據
db.person.find()
db.person.find({age:{$gte:30}})
db.person.findOne()
這裏寫圖片描述
lt>lessthen lte ->less than and equal 不大於
gt>greaterthen gte ->greater then and equal 不小於
ne>notequal or -> 關係或
$and -> 關係與

3.5 修改數據
db.person.update({name:”zhang_3”},{set:{age:25}})  
db.person.update({name:”zhang_3”},{
set:{age:25,address:”xi_an_1”}})

3.6 刪除數據
db.person.remove(修改條件)
如:
db.person.remove({name:”zhang_3”})

3.7 建索引:
db.person.ensureIndex({name:1}, {unique:true}) // 唯一索引

3.8 備份
mongodump -d person -o d:\dbpart\MongoDB\person
這裏寫圖片描述
3.9 刪除數據庫
use person
// 查看集合
show collections
// 刪除數據庫
db.dropDatabase()

3.10 恢復
mongorestore -d person d:\dbpart\MongoDB\person\person\person.bson

4 使用java操作MongoDB
4.1 使用 com.mongodb.client.MongoDatabase 類中的createCollection()來創建集合

// 創建集合
public void testConnDB() {
    try {
        // 連接到 mongodb 服務
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 連接到數據庫
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("連接MongoDB數據庫成功");
        mongoDatabase.createCollection("test");
        System.out.println("集合創建成功");

        // 關閉連接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

4.2 選擇集合

// 選擇集合
public void getCollections() {
    try {
        // 連接到 mongodb 服務
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 連接到數據庫
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("連接MongoDB數據庫成功");

        MongoCollection<Document> collection = mongoDatabase.getCollection("person");
        System.out.println("集合 test 選擇成功[" + collection.count() + "]");

        // 關閉連接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

4.3 使用com.mongodb.client.MongoCollection類的 insertMany() 方法來插入一個文檔

// 插入文檔
public void InsertDoc() {
    try {
        // 連接到 mongodb 服務
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 連接到數據庫
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("Connect to database successfully");

        MongoCollection<Document> collection = mongoDatabase.getCollection("test");
        System.out.println("集合 test 選擇成功");
        // 插入文檔
        /**
         * 1. 創建文檔 org.bson.Document 參數爲key-value的格式 2. 創建文檔集合List<Document>
         * 3. 將文檔集合插入數據庫集合中 mongoCollection.insertMany(List<Document>)
         * 插入單個文檔可以用 mongoCollection.insertOne(Document)
         */
        Document document = new Document("title", "MongoDB").append("description", "database").append("likes", 100)
                .append("by", "Fly").append("memo", "插入中文");
        List<Document> documents = new ArrayList<Document>();
        documents.add(document);
        collection.insertMany(documents);
        System.out.println("文檔插入成功");

        // 關閉連接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

4.4 使用 com.mongodb.client.MongoCollection 類中的 find() 方法來獲取集合中的所有文檔。

// 查詢文檔
public void qryDoc() {
    try {
        // 連接到 mongodb 服務
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 連接到數據庫
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("連接MongoDB數據庫成功");

        MongoCollection<Document> collection = mongoDatabase.getCollection("test");
        System.out.println("集合 test 選擇成功");

        // 檢索所有文檔
        /**
         * 1. 獲取迭代器FindIterable<Document> 2. 獲取遊標MongoCursor<Document> 3.
         * 通過遊標遍歷檢索出的文檔集合
         */
        FindIterable<Document> findIterable = collection.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next());
        }

        // 關閉連接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

4.5 修改文檔

// 修改文檔
public void updDoc() {
    try {
        // 連接到 mongodb 服務
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 連接到數據庫
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("連接MongoDB數據庫成功");

        MongoCollection<Document> collection = mongoDatabase.getCollection("test");
        System.out.println("集合 test 選擇成功");

        // 更新文檔 將文檔中likes=100的文檔修改爲likes=200
        collection.updateMany(Filters.eq("likes", 100), new Document("$set", new Document("likes", 200)));
        // 檢索查看結果
        FindIterable<Document> findIterable = collection.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next());
        }

        // 關閉連接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

4.6 刪除文檔

// 刪除文檔
public void delDoc() {
    try {
        // 連接到 mongodb 服務
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 連接到數據庫
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("連接MongoDB數據庫成功");

        MongoCollection<Document> collection = mongoDatabase.getCollection("test");
        System.out.println("集合 test 選擇成功");

        // 刪除符合條件的第一個文檔
        collection.deleteOne(Filters.eq("likes", 200));
        // 刪除所有符合條件的文檔
        collection.deleteMany(Filters.eq("memo", "插入中文"));
        // 檢索查看結果
        FindIterable<Document> findIterable = collection.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next());
        }

        // 關閉連接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章